Bas*_*sem 1 c# combobox windows-applications
在发布这个问题之前,我认为这是一个简单的问题,我搜索答案并没有找到合适的解决方案.
在我的日常工作中,我正在使用Web应用程序,可以轻松获取或设置下拉列表的值
我不能在Windows应用程序C#中做同样的事情
我有组合框和类comboItem
public class ComboItem
{
public int Key { get; set; }
public string Value { get; set; }
public ComboItem(int key, string value)
{
Key = key; Value = value;
}
public override string ToString()
{
return Value;
}
}
Run Code Online (Sandbox Code Playgroud)
假设组合框通过硬编码绑定,值为
关键:2 /价值:女性
关键:3 /价值:未知
假设我有Key = 3并且我想通过代码设置此项(其键为3),因此在加载表单时,默认情况下所选的值将为Unknown.
combobox1.selectedValue =3 //Not Working , selectedValue used to return an object
combobox1.selectedIndex = 2 //Working as 2 is the index of key 3/Unknown
Run Code Online (Sandbox Code Playgroud)
但是让我说我不知道索引,我怎样才能得到key = 3的项目的索引?
index可以通过这种方式获得价值
int index = combobox1.FindString("Unknown") //will return 2
Run Code Online (Sandbox Code Playgroud)
FindString取值而不是键,我需要像FindString这样的东西,它取一个键并返回索引
注意:这是我如何绑定我的下拉菜单
JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;
var empResult= await response.Content.ReadAsStringAsync();
List<Emp> Emps= JsonConvert.DeserializeObject<Emp[]>(empResult, jsonSerializerSettings).ToList();
foreach (var item in Emps)
{
ComboItem CI = new ComboItem(int.Parse(item.ID), item.Name);
combobox1.Items.Add(CI);
}
this.combobox1.DisplayMember = "Value";
this.combobox1.ValueMember = "Key";
Run Code Online (Sandbox Code Playgroud)
您需要设置ValueMember属性,以便ComboBox知道在使用时要处理的属性SelectedValue.默认情况下,ValueMember它将为空.所以当你设置时SelectedValue,ComboBox不知道你想要设置什么.
this.comboBox1.ValueMember = "Key";
Run Code Online (Sandbox Code Playgroud)
通常,您还可以设置DisplayMember属性:
this.comboBox1.DisplayMember = "Value";
Run Code Online (Sandbox Code Playgroud)
如果你没有设置它,它只会调用ToString()对象并显示它.在你的情况下,ToString()返回Value.
我怎样才能得到key = 3的项目的索引?
如果你想要键为3的项目,你为什么需要从组合框中获取它?您可以从组合框绑定的集合中获取它:
例如,想象一下:
var items = new List<ComboItem> { new ComboItem(1, "One"),
new ComboItem( 2, "Two") };
this.comboBox1.DataSource = items;
this.comboBox1.DisplayMember = "Value";
this.comboBox1.ValueMember = "Key";
this.comboBox1.SelectedValue = 2;
Run Code Online (Sandbox Code Playgroud)
如果我需要键为2的项目,那么这将实现:
// Use Single if you are not expecting a null
// Use Where if you are expecting many items
var itemWithKey2 = items.SingleOrDefault(x => x.Key == 2);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6244 次 |
| 最近记录: |