简体   繁体   中英

How to get database value to label filtered by combobox

I have a combobox connected to a database which shows initials of employees. Now if I select an initial, I want a label to show the name of the employee that belongs to this initial.

What's wrong with my code?

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
        SqlConnection conn = new SqlConnection(constr);
        SqlCommand cmd1 = new SqlCommand("SELECT Prename FROM Employee WHERE Initials=@Initials", conn);
        cmd1.Parameters.Add(new SqlParameter("@Initials", comboBox1.SelectedIndex.ToString()));
        SqlDataReader PrenameReader;
        try
        {
            conn.Open();
            PrenameReader = cmd1.ExecuteReader();
            while (PrenameReader.Read())
            {
                string sPrename = PrenameReader["Prename"].ToString(); 
                lblPrename.Text = sPrename;
            }

            conn.Close();
        }


        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
}

Thanks in advance!

this is your problem I think

cmd1.Parameters.Add(new SqlParameter("@Initials", comboBox1.SelectedIndex.ToString()));

change it to

cmd1.Parameters.Add(new SqlParameter("@Initials", comboBox1.SelectedValue.ToString()));

Or

cmd1.Parameters.Add(new SqlParameter("@Initials", comboBox1.SelectedText);

whichever gives proper Initials. Also I am not sure how many Values you will get from that query but if you want the first result either use Top 1 in you select query or don't read all Data as it will only get the last record's value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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