如何在数据库中添加ComboBox中的项目

时间:2015-08-14 14:09:25

标签: c# visual-studio-2013 combobox items

我试图在comboBox(cmbInstructor)中添加项目,即姓氏(instructorLN)但是,我的代码似乎不起作用。关于我哪里出错的任何想法?

private void cmbInstructor_SelectedIndexChanged(object sender, EventArgs e)
{
    MySqlConnection conn = new MySqlConnection(mycon);
    MySqlCommand cmd = new MySqlCommand("SELECT * FROM instructor WHERE instructorType ='" + labelClass.Text + "'", conn);
    string instructorLN = "";

    conn.Open();
    MySqlDataReader myReader = null;
    myReader = cmd.ExecuteReader();

    while (myReader.Read())
    {
        instructorLN = myReader["instructorLN"].ToString();
    }
    cmbInstructor.Items.Add(instructorLN);
}

1 个答案:

答案 0 :(得分:1)

据我所知,您添加最后一个SELECT返回的值。

移动你的

cmbInstructor.Items.Add(instructorLN);

以while语句作为;

while (myReader.Read())
{
    cmbInstructor.Items.Add(myReader["instructorLN"].ToString());
}

顺便说一句,你应该总是使用parameterized queries。这种字符串连接对SQL Injection攻击开放。

还可以使用using statement自动处理您的连接,命令和阅读器。

using(var conn = new MySqlConnection(mycon))
using(var cmd = conn.CreateCommand())
{
    cmd.CommandText = "SELECT * FROM instructor WHERE instructorType = @type";
    cmd.Parameters.Add("@type", labelClass.Text);

    conn.Open();
    using(var myReader = cmd.ExecuteReader())
    {
        while (myReader.Read())
        {
             cmbInstructor.Items.Add(myReader["instructorLN"].ToString());
        }
    }
}