【问题标题】:How to add combobox value out of databank MSQL如何从数据库 SQL 中添加组合框值
【发布时间】:2019-08-10 01:06:50
【问题描述】:

所以我想从数据库中添加具有值的ComboBox 项目。 我现在的代码是这样的:

//Make connection
        MySqlConnection conn = new MySqlConnection(StrConnectionstring);

        //SQL
        MySqlCommand cmd = new MySqlCommand("SELECT Classname, ClassID FROM tblClasses", conn);

        //Open connection
        conn.Open();
        MySqlDataReader DR = cmd.ExecuteReader();



        while (DR.Read())
        {
            CmbClass.DisplayMember = "Text";
            CmbClass.ValueMember = "Value";
            CmbClass.Items.Add( new { Text = Convert.ToString(DR["Classname"]), Value = Convert.ToInt16(DR["ClassID"]) });
        }

正确给出了类名,但是当我使用 cmbClass.SelectedValue 时,它没有给出任何值。

【问题讨论】:

  • DR["Classname"] 来自哪里?不是您的查询。
  • 使用DataTable.DefaultView 作为ComboBox.DataSource。或使用BindingSource(其中BindingSource.DataSource 是DataTable 或List<class>)。

标签: c# mysql winforms


【解决方案1】:

您需要在组合框中选择一些值。

另外,如果你想使用SelectedValue,你必须先使用绑定,设置DataSource of ComboBox。如果你不想这样做,那么你可以使用SelectedItem

另外,您将DisplayMemeberValueMemeber 设置在一个循环中,这是不必要的。 在循环之外执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    相关资源
    最近更新 更多