JamesM
JamesM

Reputation:

c# How do I select a list box item when I have the value name in a string?

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

Upvotes: 5

Views: 54349

Answers (8)

AKV
AKV

Reputation: 9

CheckBoxList.Items.FindByValue("Value").Selected = true;

Upvotes: 0

Four
Four

Reputation: 900

static class ControlHelper
{
    public static void SelectExactMatch(this ComboBox c, string find)
    {
        c.SelectedIndex = c.FindStringExact(find, 0);
    }
}

Upvotes: 0

Rashmi Pandit
Rashmi Pandit

Reputation: 23788

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;
            }
        }    
    }
    

Upvotes: 1

Michał Ziober
Michał Ziober

Reputation: 38635

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.");
        }
    }

Upvotes: 1

Patrick McDonald
Patrick McDonald

Reputation: 65421

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

Upvotes: 4

Nescio
Nescio

Reputation: 28403

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);

Upvotes: 16

bruno conde
bruno conde

Reputation: 48265

Try with ListBox.SetSelected method.

Upvotes: 1

Lazarus
Lazarus

Reputation: 43064

Isn't SelectedValue read/write?

Upvotes: 0

Related Questions