【问题标题】:Programmatically select an item in combobox by using its ValueMember property使用其 ValueMember 属性以编程方式选择组合框中的项目
【发布时间】:2016-04-26 14:55:01
【问题描述】:

我有一个方法可以获取ComboBox 对象和要在其项目上加载的查询。

该方法还要求另外 2 项:

1.DB表的列名并设置到ComboboxDisplayMember属性中

2.该DB表列名下每条记录的id,并设置到ComboboxValueMember属性中

public void DatabaseColumnRecordsToCombobox(ComboBox cbx, String query, String displayMember, String valueMember)
{
    try
    {
        cmd = new MySqlCommand(query, connection);
        da = new MySqlDataAdapter(cmd);
        tbl = new DataTable();
        da.Fill(tbl);
        cbx.DataSource = tbl;
        cbx.DisplayMember = displayMember;
        cbx.ValueMember = valueMember;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        this.CloseConnection();
    }
}

我通过创建一个包含 2 列、ID 及其对应名称的查询来使用该方法。并将其存储在ComboBoxDisplayMemberValueMember 中:

DatabaseColumnRecordsToCombobox(cmbSupplier, "SELECT Id, Supplier_Name FROM Supplier WHERE Enable_Flag=1 ORDER BY Supplier_Name", "Supplier_Name", "Id");

对于冗长的介绍,我深表歉意,我只想让大家在告诉我的问题之前了解我的程序是如何工作的。那么问题来了,如何使用ComboBoxValueMember属性选择DataGridView的默认项呢?

我所知道的以编程方式选择项目是使用cmbCategory.SelectedItem = "Supplier A",但我需要的是使用ValueMember 进行选择。这样我可以通过 Id 设置默认项目。

【问题讨论】:

    标签: c# combobox valuemember


    【解决方案1】:

    只需使用 SelectedValue 代替:

    comboBox1.SelectedValue = "2";
    

    一个非常简单的例子来说明我的意思:

            DataTable dt = new DataTable();
            dt.Clear();
            dt.Columns.Add("Id");
            dt.Columns.Add("Supplier_Name");
            DataRow r = dt.NewRow();
            r["Id"] = "1";
            r["Supplier_Name"] = "Supplier A";
            dt.Rows.Add(r);
            r = dt.NewRow();
            r["Id"] = "2";
            r["Supplier_Name"] = "Supplier B";
            dt.Rows.Add(r);
            r = dt.NewRow();
            r["Id"] = "3";
            r["Supplier_Name"] = "Supplier C";
            dt.Rows.Add(r);
    
            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "Supplier_Name";
            comboBox1.ValueMember = "Id";
    
            //This will set the ComboBox to "Supplier B"
            comboBox1.SelectedValue = "2";
    

    【讨论】:

    • 成功了!非常感谢你!但只是想知道是否可以为 combobox1.SelectedValue 使用整数?例如comboBox1.SelectedValue = 1。我使用了一个整数,它仍然有效,只是不知道为什么会这样。顺便说一句,我爱你男人! #nohomo
    • 哈哈没问题的人!整数应该也可以工作,因为它是对象类型。您应该能够使用与 ValueMember 中的类型相同的类型。
    猜你喜欢
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2014-03-02
    相关资源
    最近更新 更多