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