简体   繁体   中英

selected index value in C# with combobox with database

I am new in c# and I have a question. I want to select a value from a combobox and it should show in a label it's age.

What I do is this:

 public void FillCombo()
        {
           SqlDataAdapter adap = new SqlDataAdapter("Select * from customers",con);

            DataTable dt = new DataTable();
            adap.Fill(dt);
            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "name";
            comboBox1.ValueMember = "id";

        }

  private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            con.Open();

           SqlCommand cmd1 = new SqlCommand("Select * from customers where name=@name ", con);
            cmd1.Parameters.AddWithValue("@name",comboBox1.SelectedItem));

           int i= cmd1.ExecuteNonQuery();

            if (i > 0)
            {
               SqlDataReader sqlrdr = cmd1.ExecuteReader();
            while (sqlrdr.Read())
            {
                String age= sqlrdr["age"].ToString();
                label1.Text = age;
            }

            }

 else{
MessageBox.Show("no value");
}

con.Close();
    }

It shows no value message , even if i have values in database. What can I do?

When you set the DataSource to a DataTable then every item in the combobox is a DataRowView . So you already have the info about the age of the current customer in the combobox. No need to make another call to the database.

You just need to use the SelectedItem property to retrieve the info about the age field or any other field present in the DataSource

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    DataRowView rv = l.SelectedItem as DataRowView;

    // For safety, always check for null. 
    // It is possible that SelectedIndexChanged 
    // will be called even when there is no selection in the combobox
    if(rv != null)
    {
        label1.Text = rv["age"].ToString();
        ....
    }
}

Try this to obtain index,value and selected name:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox cmb = (ComboBox)sender;
        int selectedIndex = cmb.SelectedIndex;
        int selectedValue = (int)cmb.SelectedValue;
        ComboboxItem selectedName = (ComboboxItem)cmb.SelectedItem;
    }

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