Sql组合框值 [英] Sql combo box values
本文介绍了Sql组合框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好。
我需要的是一个组合框,用于显示SQL数据库中列的所有值。这部分正在运作。我需要的是所选值不是名称而是项目的ID。
string conString = @ CONNECTION STRING HERE;密码= PWD;
SqlConnection conn = new SqlConnection(conString);
DataSet ds = new DataSet();
尝试
{
conn.Open();
SqlCommand cmd = new SqlCommand( select *来自Devices,conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
comboBox1.DisplayMember = 地址;
comboBox1.ValueMember = ID;
comboBox1.DataSource = ds.Tables [ 0 ];
label7.Text = comboBox1.ValueMember;
}
catch (例外情况)
{
// 异常消息
}
}
地址显示在组合中,但看起来值仍然是文本而不是ID。
我做错了什么?
我尝试了什么:
comboBox1.DisplayMember = 地址跨度>;
comboBox1.ValueMember = ID;
解决方案
尝试使用 ListControl.SelectedValue Property(System.Windows.Forms)|微软文档 [ ^ ]
例如
label7.Text = comboBox1.SelectedValue.ToString();
请记住通过调查例如 ComboBox.SelectedIndex属性(System.Windows.Forms的)?|微软文档 [ ^ ]
写下来就像
label7.Text = comboBox1的.text;
Hi.
What I need is a combo box to show all the values of a column from my SQL database. This part is working. What i need is the selected value not to be the name but the ID of the item.
string conString = @"CONNECTION STRING HERE; Password = PWD";
SqlConnection conn = new SqlConnection(conString);
DataSet ds = new DataSet();
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("select * from Devices", conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
comboBox1.DisplayMember = "Address";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = ds.Tables[0];
label7.Text = comboBox1.ValueMember;
}
catch (Exception ex)
{
//Exception Message
}
}
The address are shown in the combo, but it appears the value is still the text rather then the ID.
What have i done wrong?
What I have tried:
comboBox1.DisplayMember = "Address";
comboBox1.ValueMember = "ID";
解决方案
Instead of fetching the ValueMember, try to use ListControl.SelectedValue Property (System.Windows.Forms) | Microsoft Docs[^]
For example
label7.Text = comboBox1.SelectedValue.ToString();
Remember to test if a selection has been made by investigating for example ComboBox.SelectedIndex Property (System.Windows.Forms) | Microsoft Docs[^]
Just write down like label7.Text = comboBox1.Text;
这篇关于Sql组合框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文