tags:

views:

1129

answers:

6

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

A: 

Isn't SelectedValue read/write?

Lazarus
I've tried lstbox.selectedvalue = strItem; but that didn't seem to work for me.
Is this WinForms or WebForms?
Lazarus
+3  A: 
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

Patrick McDonald
A: 

Try with ListBox.SetSelected method.

bruno conde
+4  A: 
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);
Nescio
Or you can do lb.SelectedIndex = lb.FindStringExact(fieldValue);
Rashmi Pandit
+1  A: 

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.");
        }
    }
mykhaylo
Better message would be "Item not found."
Rashmi Pandit
+1, for also providing a test method. Good programming habit.
Brett McCann
A: 

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:

  1. lb.SelectedValue = fieldValue;

  2. lb.SelectedIndex = lb.FindStringExact(fieldValue);

  3. 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;
            }
        }    
    }
    
Rashmi Pandit