Reputation: 165
I'm trying to select ListBox items through C#. I am not able to select multiple items, it always select the last value which is in my selected items list.
I tried to loop through each ListBoxItem
and check if it exists in my selected items list or not.
List<int> SelectedItems = new List<int>();
SqlCommand cmd = new SqlCommand(Query, con)
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
SelectedItems.Add(Convert.ToInt32(dr["RecordId"].ToString()));
}
for (int i = 0; i < listbox.Items.Count; i++) {
int x = Convert.ToInt32(listbox.Items[i].Value.ToString());
if(SelectedItems.Contains(x)){
listbox.SelectionMode = listbox.Multiple;
listbox.SelectedIndex = i;
}
}
I need to select multiple items not only the last selected value. What am I doing wrong?
Upvotes: 2
Views: 1378
Reputation: 878
You can use this:
LblDisplay.Text = "";
lstPromote_products.SetItemChecked(4, true);
chkRestricted.Checked = true;
Upvotes: 0
Reputation: 1105
Instead of setting SelectedIndex
property, try adding items with listbox.SetSelected
with listbox.SetSelected(x,true);
Upvotes: 2