简体   繁体   English

C#-用MySql数据库填充ComboBox的意外结果

[英]C# - unexpected result in populating ComboBox with MySql database

I my class DBConnect , I have this function to populate a ComboBox to database based on input query: 在我的类DBConnect ,我具有基于输入查询将ComboBox填充到数据库的功能:

public void POPULATE_COMBOBOX(string query, ComboBox myComboBox)
{
    if (this.OpenConnection() == true)
    {
        MySqlCommand cmd = new MySqlCommand(query, connection);

        MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
        DataTable myDataTable = new DataTable();

        adapter.Fill(myDataTable);
        myComboBox.DataSource = myDataTable; 

        this.CloseConnection();
    }
}

And here's how I use it 这就是我的使用方式

DBConnect.POPULATE_COMBOBOX("SELECT NAME FROM users", comboBox_Name); DBConnect.POPULATE_COMBOBOX(“来自用户的选择名称”,comboBox_Name);

I have 3 rows in column NAME , and I expect those 3 names will be displayed in my comboBox_Name . 我在“ NAME列中有3行,我希望这3个名称将显示在我的comboBox_Name However instead, I got 3 lines of System.Data.DataRowView in my combobox. 但是,相反,我的组合框中有3行System.Data.DataRowView Any idea how to convert those DataRowView to string? 任何想法如何将那些DataRowView转换为字符串?

You have to tell combobox what column to display. 您必须告诉组合框要显示的列。

//Preparation
var dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add("Name1");
dt.Rows.Add("Name2");

//Setup data binding
myComboBox.DataSource = dt.DefaultView;
myComboBox.DisplayMember = "Name";
myComboBox.ValueMember = "Name";

Then SelectedItem gets the actual ComboBox item (in this case a DataRowView), whereas SelectedValue gets the value of the property you specified as the ValueMember of the ComboBox 然后, SelectedItem获取实际的ComboBox项(在本例中为DataRowView),而SelectedValue获取您指定为ComboBox的ValueMember的属性的值

Or another way how to populate your ComboBox is: 或如何填充您的ComboBox另一种方法是:

MySqlDataReader sqlReader = cmd.ExecuteReader();

while (sqlReader.Read())
{
    myComboBox.Items.Add(sqlReader["Name"].ToString());
}

sqlReader.Close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM