【问题标题】:C# Combobox item text change?C# 组合框项目文本更改?
【发布时间】:2017-11-06 07:53:40
【问题描述】:

我正在制作包含从 DB 中添加的家庭地址列表的组合框,我正在尝试实现更改组合框中当前地址的文本的选项。例如,它现在从 db 中获取 adressID,但我想添加一个选项来调用它,例如“Adress 1”,而不仅仅是 adressID。我已经尝试了一些选项,来自谷歌之前的建议示例,但是我收到此错误:设置 DataSource 属性时无法修改 Items 集合。 因为我正在使用数据源。有人知道如何解决这个问题吗?

这是我的代码:

        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";

    }

【问题讨论】:

    标签: c# combobox datasource


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

       BindingSource Adresses = new BindingSource();
       Adresses.DataSource = dt;
      
       comboBox1.DataSource = Adresses;
       comboBox1.DisplayMember = "adressID";
       comboBox1.ValueMember = "adressID";
      

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

      Adresses.ResetBindings(true);
      

      更新组合的数据。

      【讨论】:

        猜你喜欢
        • 2013-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-18
        • 2011-04-12
        • 2011-08-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多