我想用数据库字段填充组合框

时间:2017-05-26 14:15:49

标签: c# mysql combobox

我的代码有点问题。我想用数据库字段填充一个组合框:

     const string connMysql = "DataSource=localhost; Database=ph; Uid=root; Pwd=;";
            myConn = new MySqlConnection(connMysql);
            string cad = "SELECT answers FROM `questions` WHERE (`test_num` = '1')";
            myConn.Close();
            myConn.Open();
            myCommand = new MySqlCommand(cad, myConn);
            myReader = myCommand.ExecuteReader();            
            if (myReader.Read())
            {
                CB1.Items.Clear();
                CB1.Items.Add(myReader[0].ToString());
}

我使用此功能并在combobox中保留1个字段,我想填写“答案”的所有内容。

2 个答案:

答案 0 :(得分:0)

正如其他人所说,你只是添加了一个字段,迭代查询工作。

 const string connMysql = "DataSource=localhost; Database=ph; Uid=root; Pwd=;";
        myConn = new MySqlConnection(connMysql);
        string cad = "SELECT answers FROM `questions` WHERE (`test_num` = '1')";
        myConn.Close();
        myConn.Open();
        myCommand = new MySqlCommand(cad, myConn);
        myReader = myCommand.ExecuteReader();     
        int i = 0;
        CB1.Items.Clear(); //Clear the Combo box once before adding values
        while(myReader.Read())
        {
            CB1.Items.Add(myReader[i].ToString());
            i++;
        }

答案 1 :(得分:0)

感谢所有答案,这就是我所做的:

        const string connMysql = "DataSource=localhost; Database=ph; Uid=root; Pwd=;";
        myConn = new MySqlConnection(connMysql);
        string cad = "SELECT answers FROM `questions` WHERE (`test_num` = '1');";
        myConn.Close();
        myConn.Open();
        myCommand = new MySqlCommand(cad, myConn);
        myReader = myCommand.ExecuteReader();
        CB1.Items.Clear();
        while (myReader.Read())
        {
            CB1.Items.Add(myReader[0].ToString());
            }

combobox填写“答案”的所有内容