c# - CSharp .NET 3.5 Windows 窗体数据绑定(bind)组合框到列表<>

标签 c# data-binding combobox winforms

好吧,首先我有以下代码工作..虽然我的问题是这样的;我应该像下面的示例一样编码组合框数据绑定(bind),还是有更简单/更有效的方法?

首先,我需要操作从数据库返回的结果以显示更具描述性的含义:

(我正在使用键/值对的基本类)

class WashBayDesc
    {
        public string Key { get; set; }
        public string Text { get; set; }
    }

现在,我从数据读取器检索数据并进行所需的操作,然后将结果添加到列表项:

    var washbaydata = new List<WashBayDesc>();

    //  Read through the available cashboxes and populate a list/combobox
    while (rdr.Read())
    {
        string sWashBayDesc = null;
        string sWB = rdr["washbay"].ToString();
        if (sWB.StartsWith("3"))
        {
            sWashBayDesc = "Bay " + sWB.Substring(1);
        }
        else
        {
            sWashBayDesc = "Auto " + sWB.Substring(1);
        }

        washbaydata.Add(new WashBayDesc { Key = sWB, Text = sWashBayDesc });
    }

        //  Now bind the hashtable (with our bay selectors) to the dropdown
        cmbCashBoxes.DataSource = washbaydata;
        cmbCashBoxes.ValueMember = "Key";
        cmbCashBoxes.DisplayMember = "Text";

所以..我的想法是我可以简单地将ComboBox数据源绑定(bind)到washbaydata列表对象..这工作得很好。

下一部分是检索所选项目的值(即不是文本描述,而是值或键本身)。我认为这可能看起来不太正确,尽管它再次有效......

    WashBayDesc myRes = new WashBayDesc();
    myRes = (WashBayDesc)cmbCashBoxes.SelectedItem;
    string sWashBayCashBox = myRes.Key;

所以结果是我的字符串 sWashBayCashBox 具有选定的键...

我想它可以工作,这很好,但是有没有更简单/更干净的方法?

最佳答案

string sWashBayCashBox = (string)cmbCashBoxes.SelectedValue;

关于c# - CSharp .NET 3.5 Windows 窗体数据绑定(bind)组合框到列表<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1871534/

相关文章:

c# - 脚手架 Controller mvc 5 时出错

c# - 检查图片框数组中的所有图片框 - 西洋跳棋游戏?

c# - 使用 StringFormat 将字符串添加到 WPF XAML 绑定(bind)

c# - 带有 PART_Editor 作为 Itemssource 项的 WPF ComboBox

c# - 如何在运行时根据屏幕分辨率自动调整表单窗口大小(设计期间创建的窗口尺寸太大)

c# - 如何绑定(bind) ComboBox 以便 displaymember 是源数据表的 2 个字段的 concat?

c# - 如何反序列化 Nullable<bool>?

c# - 查找匹配字符串算法

wpf - 在 WPF 中绑定(bind) DataGridTextColumn 可见性属性

WPF 数据绑定(bind) : How do I access the "parent" data context?