I have a string 'item3' and a listbox with 'item1,item2,item3,item4', how do I select item3 in the list box when I have the item name in a string?
Thanks
I have a string 'item3' and a listbox with 'item1,item2,item3,item4', how do I select item3 in the list box when I have the item name in a string?
Thanks
listBox.FindStringExact("item3");
Returns the index of the first item found, or ListBox.NoMatches if no match is found.
you can then call
listBox.SetSelected(index, true);
to select this item
int index = listBox1.FindString("item3");
// Determine if a valid index is returned. Select the item if it is valid.
if (index != -1)
listBox1.SetSelected(index,true);
Maybe like this:
public bool SelectItem(ListBox listBox, string item)
{
bool contains = listBox.Items.Contains(item);
if (!contains)
return false;
listBox.SelectedItem = item;
return listBox.SelectedItems.Contains(item);
}
Test method:
public void Test()
{
string item = "item1";
if (!SelectItem(listBox, item))
{
MessageBox.Show("Item not found.");
}
}
SelectedValue will work only if you have set the ValueMember for the listbox.
Further, even if you do set the ValueMember, selectedValue will not work if your ListBox.Sorted = true.
Check out my post on Setting selected item in a ListBox without looping
You can try one of these approaches:
lb.SelectedValue = fieldValue;
lb.SelectedIndex = lb.FindStringExact(fieldValue);
This is a generic method for all listboxes. Your implementation will change based on what you are binding to the list box. In my case it is DataTable.
private void SetSelectedIndex(ListBox lb, string value)
{
for (int i = 0; i < lb.Items.Count; i++)
{
DataRowView dr = lb.Items[i] as DataRowView;
if (dr["colName"].ToString() == value)
{
lb.SelectedIndices.Add(i);
break;
}
}
}