按值选择组合框项目 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14181441/
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
select combobox item by value C#
提问by yaron.g
I have a combobox , bound to Datatable
and have the following properties:
我有一个组合框,绑定到Datatable
并具有以下属性:
cboCars.DisplayMember = "carLiscen";
cboCars.ValueMember = "carNo";
How can I select the DisplayMember
when I know the ValueMember
?
DisplayMember
当我知道时如何选择ValueMember
?
采纳答案by sa_ddam213
If you have a ValueMember
set you can select using SelectedValue
如果你ValueMember
有一套,你可以选择使用SelectedValue
cboCars.DisplayMember = "carLiscen";
cboCars.ValueMember = "carNo";
cboCars.SelectedValue = "valuemember value";
回答by Alireza Noori
You can use cboCars.SelectedValue = "123";
property for this. Here's a code snippet which will show it in action.
您可以cboCars.SelectedValue = "123";
为此使用属性。这是一个代码片段,它将显示它的实际效果。
public void Test()
{
ArrayList info = new ArrayList();
info.Add(new CarInfo { CarLiscen = 123456, CarNo = 123});
info.Add(new CarInfo { CarLiscen = 234567, CarNo = 234 });
cboCars.DataSource = info;
cboCars.DisplayMember = "CarLiscen";
cboCars.ValueMember = "CarNo";
cboCars.SelectedValueChanged +=
delegate(object sender, EventArgs e)
{
if (cboCars.SelectedIndex != -1)
{
this.Text = cboCars.SelectedValue.ToString();
}
};
cboCars.SelectedValue = 234;
}
And if you wonder what is the definition of CarInfo
. Here's its code (which is fairly simple):
如果你想知道CarInfo
. 这是它的代码(相当简单):
public class CarInfo
{
public int CarLiscen { get; set; }
public int CarNo { get; set; }
}
Hope this helps.
希望这可以帮助。
回答by Joshi
You can search for the correct item and set it to that, very simple:
您可以搜索正确的项目并将其设置为该项目,非常简单:
cbTEST.SelectedIndex = cbTEST.FindStringExact("your search string here");
or select an item based on an ListViewItem:
或基于 ListViewItem 选择一个项目:
cbTEST.SelectedIndex = cbTEST.FindStringExact(lvTEST.SelectedItems[0].SubItems[0].Text);
thats it. very simple!
就是这样。很简单!
回答by Teezy7
Hi Guys the best way if searching for a text or value is
嗨,伙计们,如果搜索文本或值,最好的方法是
int Selected;
int count = ComboBox1.Items.Count;
for (int i = 0; (i<= (count - 1)); i++)
{
ComboBox1.SelectedIndex = i;
if ((string)(ComboBox1.SelectedValue) == "SearchValue")
{
Selected = i;
}
}
ComboBox1.SelectedIndex = Selected;