簡體   English   中英

C#組合框項目文本更改了嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM