我是c#新手,我有一个问题。 我想从组合框中选择一个值,它应该在标签中显示它的年龄。
我所做的是这样的:
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();
}
它不显示任何值消息,即使我在数据库中有值。我能做什么?
将数据源设置为数据表时,组合框中的每个项目都是 DataRowView。因此,您已经在组合框中获得了有关当前客户年龄的信息。无需再次调用数据库。
只需使用 SelectedItem 属性来检索有关年龄字段或数据源中存在的任何其他字段的信息
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();
....
}
}
尝试获取索引,值和所选名称:
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;
}