简体   繁体   English

根据 ValueMember 从 Combobox 获取索引

[英]Get index from Combobox based on ValueMember

I have a Combobox that stores a name as DisplayMember and an id as ValueMember.我有一个 Combobox,它将name存储为 DisplayMember,将id存储为 ValueMember。 On my database, I store only the id .在我的数据库中,我只存储id

How can I set it to the correct index by id ?如何通过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.不起作用,因为它不按 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 .您不需要根据选择的值查找索引,只需设置SelectedValue即可。

Example 1 - Set SelectedValue示例 1 - 设置 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.虽然上面的示例显示了如何使用所选值设置选择,但如果出于任何原因您想根据该值查找项目或所选索引,则需要使用此GetItemValue扩展方法并基于该方法查找项目。

Example 2 - Get Item by Value → Set SelectedItem示例 2 - 按值获取项目 → 设置 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示例 3 - 按值获取索引 → 设置 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM