从.NET WinForms的组合框中获取信息 [英] Get back information from combo box in .NET WinForms

查看:63
本文介绍了从.NET WinForms的组合框中获取信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是有关WinForms中的组合框。因此,假设我们有一个具有许多字段的通用列表和SingleItem类。例如,

My question is about combo boxes in WinForms. So assume we have a generic list and SingleItem class with a lot of fields. For example

class SingleItem{
    public int val1;
    public int val2;
    public string str;
    public override string ToString(){
        return str;
    }
};
List<SingleItem> listOfItems;

假设我们有 comboBox 变量。我以这种方式将项目添加到comboBox

Assume, that we have comboBox variable. I'm adding items to comboBox this way

foreach(SingleItem item in listOfItems){
    comboBox.Items.Add(item);
}

然后,当用户完成选择项目时,我们需要获取另一个字段从选定的项目。例如,我需要这样的东西

And then, when user finished choosing an item, we need to get another field from chosen item. For example, i need something like this

comboBox.SelectedItem.val1; // where val1 is field of SingleItem class

的字段。这就是问题所在。我曾尝试用Google搜索这个问题,但没有找到有价值的答案。我也尝试进行类型转换,但是失败了。我当前的解决方案是在列表中搜索选定的值,但是该解决方案具有O(n)的复杂度并且不够好。谢谢

That is the problem. I tried to Google this problem, but didn't find valuable answer for my question. I also tried to do a type conversion, but it fails. My current solution is searching selected value in list, but this solution have O(n) complexity and not good enough. Thanks

推荐答案

这是我的处理方式:

class SingleItem
{
    public int val1 { get; set; }
    public int val2 { get; set; }
    public string str { get; set; }
    public override string ToString()
    {
        return str;
    }

}

...

 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var obj = ((SingleItem)comboBox1.SelectedItem).val1; 
}

欢呼声

这篇关于从.NET WinForms的组合框中获取信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆