EllieK EllieK - 1 month ago 11
C# Question

C# Listbox Value is Null After Setting SelectedValue

I have created a listbox based on a database table where the DisplayMember items of the listbox are created via string concatenation and the ValueMember items represents the bigInt PK from the table. The listbox is bound to a Text/Value object as shown below.

List<ComboSearchItems> csi = new List<ComboSearchItems>();
foreach(var i in q)
{
ComboSearchItems ci = new ComboSearchItems(String.Concat(i.Id, " - ", i.Name, " - ", i.CompanyName), i.Id);
csi.Add(ci);
}

lstCompany.DataSource = csi;
lstCompany.DisplayMember = "Text";
lstCompany.ValueMember = "Value";
lstCompany.SelectedIndex = 0;
lstCompany.Refresh();

public class ComboSearchItems
{
public string Text { get; set; }
public Int64 Value { get; set; }

//Constructor
public ComboSearchItems(string t, Int64 v)
{
Text = t;
Value = v;
}
}


The listbox is populated and displays correctly but when I attempt to set the SelectedValue property via the code below the listbox's SelectedValue changes to null.

lstCompany.SelectedValue = 16844;

Answer

When setting the SelectedValue of a listbox whose value are integers the new value must be of the same type of integer. Attempting to set an Int64 value without explicitly sending an Int64 type will result in a silent failure which causes the listbox's SelectedValue to be set to null.

The following examples will set the SelectedValue

 lstCompany.SelectedValue = Convert.ToInt64(4251);

 lstCompany.SelectedValue = 4251L;

The following code will silently fail and set the listbox's SelectedValue to null

 lstCompany.SelectedValue = 4251;
Comments