C#组合框项目文本更改?

C#组合框项目文本更改?,c#,combobox,datasource,C#,Combobox,Datasource,我正在制作combobox,其中包含从DB添加的主地址列表,我正在尝试实现更改combobox中当前地址的文本的选项。例如,它现在的adressID是从db获取的,但我想添加一个选项来调用它,例如“Adress 1”,而不仅仅是adressID我尝试了以前谷歌推荐的示例中的一些选项,但我得到了一个错误:设置DataSource属性时无法修改Items集合。因为我正在使用DataSource。有人知道如何解决这个问题吗 这是我的代码: private void getAdr()

我正在制作combobox,其中包含从DB添加的主地址列表,我正在尝试实现更改combobox中当前地址的文本的选项。例如,它现在的adressID是从db获取的,但我想添加一个选项来调用它,例如“Adress 1”,而不仅仅是adressID我尝试了以前谷歌推荐的示例中的一些选项,但我得到了一个错误:设置DataSource属性时无法修改Items集合。因为我正在使用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";

    }

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

当您设置数据源属性时,您必须更改的是该属性,并且您的更改自动在组合框中可见

为此,我建议您使用BindingSource对象,如下所示:

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

 comboBox1.DataSource = Adresses;
 comboBox1.DisplayMember = "adressID";
 comboBox1.ValueMember = "adressID";
更改dt对象中的某些数据时,应调用:

Adresses.ResetBindings(true);
更新组合的数据