我有一个combobox
cmbCity
和textbox
txtReference
。在表单加载时,组合框从我设法完成的数据库中检索城市。我希望文本框更改参考号。存储在数据库中,在我需要帮助的组合框中更改所选城市。我正在使用 Visual Studio 2012 和 SSMS 2012。
问问题
2708 次
2 回答
0
使用SelectedIndexChanged
事件:
private void cmbCity_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=YourSERVER;Initial Catalog=YourDataBaseName;User ID=DBUserName;Password=DBPassword");
SqlCommand com = new SqlCommand("select top 1 * from yourTable where someCondition=true",con);
SqlDataAdapter adp = new SqlDataAdapter(com);
DataTable dt = new DataTable();
adp.Fill(dt);
txtReference.Text = dt.Rows[0]["refrence_no"].ToString();
}
在每个选择上查询数据库并不是一个明智的想法 - 但是我沿着你提出问题的方式进行。
于 2014-03-19T10:27:15.197 回答
0
在表单加载中,您可以将 a 附加DataTable
到combobox.datasource
,然后设置ValueMember
and DisplayMember
。之后,combobox selectedindexchange
您将管理ValueMember
. 代码是这样的:
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection sql = new SqlConnection("connString");
SqlCommand cmd = new SqlCommand("SELECT * FROM myTable;",sql);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
cmbCity.DataSource = dt;
cmbCity.DisplayMember = "cityname";
cmbCity.ValueMember = "refrence_no";
txtReferenceNo.Text = cmbCity.SelectedItem.ToString();
}
private void cmbCity_SelectedIndexChanged(object sender, EventArgs e)
{
txtReferenceNo.Text = cmbCity.SelectedItem.ToString();
}
于 2014-03-19T10:57:56.317 回答