vb.net 在 ComboBox 的 ValueMembers 中搜索一个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20414956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:02:20  来源:igfitidea点击:

Search ComboBox's ValueMembers for a value

vb.netcomboboxindexingfindkey-value

提问by Morteza Bashardoost

I have a ComboBox (myCombo) with following features:

我有一个 ComboBox (myCombo) 具有以下功能:

Index     ValueMember     DisplayMember
 0           11             A
 1           34             H
 2           36             J
 3           85             W
 4           99             M

I want to find the index of a ValueMember in the ComboBox.

我想在 ComboBox 中找到 ValueMember 的索引。

myCombo.FindString() searches within the DisplayMembers, But i want to search within the ValueMembers.

myCombo.FindString() 在 DisplayMembers 中搜索,但我想在 ValueMembers 中搜索。

回答by T.S.

Lets pretend that Items in your combo are of unanimous type. Sorry for c# but it is really close to VB

让我们假设您组合中的项目是一致类型的。对不起 c# 但它真的很接近 VB

Setup your combo in constructor:

在构造函数中设置你的组合:

comboBox1.Items.Add(new { Name = "a", Val = 35 });
comboBox1.Items.Add(new { Name = "b", Val = 30 });
comboBox1.Items.Add(new { Name = "c", Val = 256 });
comboBox1.ValueMember = "Val";
comboBox1.DisplayMember  = "Name";

Then, on click I am looking for an index of item with value 256:

然后,单击我正在查找值为 256 的项目索引:

private void button1_Click(object sender, EventArgs e)
{
    for (int i = 0; i < comboBox1.Items.Count; i++)
    {
        if ((int)comboBox1.Items[i].GetType().GetProperty("Val").GetValue(comboBox1.Items[i]) = 256)
        {
            MessageBox.Show("index: " + i.ToString());
        }
    }

 }

Here I am using reflection to get the value of the property of unanimous type. If you know the type of the object you use - it even easier - use DirectCast (this is VB):

这里我使用反射来获取一致类型属性的值。如果你知道你使用的对象的类型 - 更容易 - 使用 DirectCast(这是 VB):

If DirectCast(comboBox1.Items(i), <known_type>).Val = 256 Then...

Main thing here is that in this line, I get the item property and get its value and compare to supplied value (in VB):

这里的主要内容是,在这一行中,我获取 item 属性并获取其值并与提供的值进行比较(在 VB 中):

CInt(comboBox1.Items(i).GetType().GetProperty("Val").GetValue(comboBox1.Items(i))) = <your int value>

回答by user2260011

Try this:

尝试这个:

(For index = 0 To comboBox1.Items.Count - 1
            comboBox1.SelectedIndex = index
            Dim dr As DataRowView = TryCast(Me.BindingContext(comboBox1.DataSource).Current, DataRowView)
            If dr(1).ToString() = "your Value" Then
                Exit For
            End If
        Next)