0

Im trying to add items in the comboBox (cmbInstructor) namely the last names (instructorLN) however, my code does not seem to work. Any ideas on where I went wrong?

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 Answer 1

1

As far as I can see, you are adding only last value that your SELECT returns.

Move your

cmbInstructor.Items.Add(instructorLN);

line into to the while statement as;

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

By the way, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

Also use using statement to dispose your connection and command and reader automatically.

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());
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the help...but it seems that the items still wont show
@jgf Why you using this code in SelectedIndexChanged event of your combobox? Did you debug your code and see what's going on?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.