Hi, I have a multi-select listbox which I am binding to a DataTable. DataTable contains 2 columns description and value.
Here's the listbox populating code:
DataTable copytable = null;
copytable = GlobalTable.Copy(); // GlobalTable is a DataTable
copytable.Rows[0][0] = "--ALL--";
copytable.Rows[0][1] = "--ALL--";
breakTypeList.DataSource = copytable;
this.breakTypeList.DisplayMember = copytable.Columns[0].ColumnName; // description
this.breakTypeList.ValueMember = copytable.Columns[1].ColumnName; // value
this.breakTypeList.SelectedIndex = -1;
I am setting description as the DisplayMember and value as the ValueMember of the ListBox. Now depending on what the value is passed I need to set the selected item in the ListBox.
Here's my code:
ListBox lb = c as ListBox;
lb.SelectedValue = valuePassedByUser;
which is not working. Hence I have to resort to the code below (where I loop through all the items in the list box)
for (int i = 0; i < lb.Items.Count; i++)
{
DataRowView dr = lb.Items[i] as DataRowView;
if (dr["value"].ToString() == valuePassedByUser)
{
lb.SelectedIndices.Add(i);
break;
}
}
I would like to know what is missing/ erroneous in my code. Why is lb.SelectedValue = valuePassedByUser; selecting incorrect items?