C#Combobox项目文本更改?

时间:2017-06-05 13:57:48

标签: c# combobox datasource

我正在制作组合框,其中包含来自DB的已添加主页地址的列表,我正在尝试实现更改当前地址在组合框中调用的文本的选项。例如,它现在从db中获取adressID,但是我想添加一个选项来调用它,例如“Adress 1”而不仅仅是adressID .. 我尝试过谷歌的建议示例之前的一些选项,但是我收到此错误:设置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";

    }

2 个答案:

答案 0 :(得分:0)

我认为你应该实现组合框的TextChanged事件。当用户更改addressID时,您应该使用SqlCommand更新数据库,然后重新加载数据源以刷新组合框项。

答案 1 :(得分:0)

设置数据源属性时,必须更改的是该属性,并自动在组合中显示您的更改。

为此,我建议你像这样使用BindingSource对象:

 BindingSource Adresses = new BindingSource();
 Adresses.DataSource = dt;

 comboBox1.DataSource = Adresses;
 comboBox1.DisplayMember = "adressID";
 comboBox1.ValueMember = "adressID";

当您更改dt对象中的某些数据时,您应该调用:

Adresses.ResetBindings(true);

更新组合的数据。

相关问题