[英]C# Combobox item text change?
我正在制作包含来自DB的添加的Home地址列表的组合框,我正在尝试实现用于更改组合框中当前地址的文本的选项。 例如,现在从数据库中获取了它的adressID,但是我想添加一个选项来调用它,例如“ Adress 1”,而不仅仅是adressID。。 我已经尝试了Google推荐示例之前的一些选项,但是我知道了错误:设置了DataSource属性后,无法修改项目集合。 因为我正在使用数据源。 有人对如何解决这个问题有想法吗?
这是我的代码:
private void getAdr()
{
string connStr = "Data Source=MARINCHI\\SQLEXPRESS;Initial Catalog=login1;Integrated Security=True";
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand getAdr = new SqlCommand("SELECT adressID, userID, adress, floor,city, state, country, zipcode FROM userAdress where userID = @userID", conn);
SqlParameter parUserID = new SqlParameter("@userID", Login.id);
getAdr.Parameters.Add(parUserID);
getAdr.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(getAdr);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "adressID";
comboBox1.ValueMember = "adressID";
textBox5.DataBindings.Add("Text", dt, "adress");
textBox6.DataBindings.Add("Text", dt, "floor");
textBox7.DataBindings.Add("Text", dt, "city");
textBox8.DataBindings.Add("Text", dt, "state");
textBox9.DataBindings.Add("Text", dt, "country");
textBox10.DataBindings.Add("Text", dt, "zipcode");
comboBox1.Items[comboBox1.SelectedIndex] = "Adress 1";
}
我认为您应该实现组合框的TextChanged事件。 当用户更改addressID时,应使用SqlCommand更新数据库,然后重新加载数据源以刷新组合框项目。
设置数据源属性时,您必须更改的是该属性,并且您的更改自动在组合中可见。
为此,我建议您使用BindingSource对象,如下所示:
BindingSource Adresses = new BindingSource();
Adresses.DataSource = dt;
comboBox1.DataSource = Adresses;
comboBox1.DisplayMember = "adressID";
comboBox1.ValueMember = "adressID";
当您更改dt对象中的某些数据时,应调用:
Adresses.ResetBindings(true);
更新组合数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.