1

I have a Combobox that stores a name as DisplayMember and an id as ValueMember. On my database, I store only the id.

How can I set it to the correct index by id?

Example code:

Combobox.SelectedIndex = Combobox.FindByValueMember("10");

The best I could find was this question, but the most voted answer did not undestand what the question was.

int index = comboref.Items.IndexOf("string");

Does not work, as it does not search by ValueMember.

This answers it but I'm wondering if there might be a better way of doing this.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
João
  • 449
  • 4
  • 18

1 Answers1

5

You don't need to find the index based on the selected value, just set SelectedValue.

Example 1 - Set SelectedValue

private void Form1_Load(object sender, EventArgs e)
{
    comboBox1.DataSource = Enumerable.Range(1, 5)
        .Select(x => new { Name = $"Product {x}", Id = x }).ToList();
    comboBox1.DisplayMember = "Name";
    comboBox1.ValueMember = "Id";
}
private void button1_Click(object sender, EventArgs e)
{
    comboBox1.SelectedValue = 3;
}

While above example shows how to set the selection using the selected value, if for any reason you want to find the item or selected index based on the value, then you need to use this GetItemValue extension method and find the item base on that.

Example 2 - Get Item by Value → Set SelectedItem

private void button1_Click(object sender, EventArgs e)
{
    var value = 3;
    var item = comboBox1.Items.Cast<Object>()
        .Where(x => comboBox1.GetItemValue(x).Equals(value))
        .FirstOrDefault();
    comboBox1.SelectedItem = item;
}

Example 3- Get Index by Value → Set SelectdIndex

private void button1_Click(object sender, EventArgs e)
{
    var value = 3;
    var item = comboBox1.Items.Cast<Object>()
        .Where(x => comboBox1.GetItemValue(x).Equals(value))
        .FirstOrDefault();
    var index = comboBox1.Items.IndexOf(item);
    comboBox1.SelectedIndex = index;
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Thanks for the examples. Setting SelectedValue worked for me, but not as suggested in the first example with an Int. I had to do `comboBox1.SelectedValue = value.ToString()` otherwise it would go null. – João Jan 20 '20 at 14:59
  • 1
    You're welcome. The type in my example is `int` so no need to `ToString`. It should follow the same type that you set in`ValueMember` field of the object in `DataSource`. – Reza Aghaei Jan 20 '20 at 15:01
  • @JoãoNunes Set `comboBox1.DataSource = ...` last. – T.S. Jan 20 '20 at 16:14