ComboBox 使用資料繫結時 Sorted 屬性的bug

來源:互聯網
上載者:User

調查一個奇怪的系統異常時發現的這個bug,現象就是使用者在ComboBox裡面選擇一項後,程式在SelectIndexChanged 事件中根據使用者選擇重新整理資料時出現錯誤。跟蹤調試後才發現原來是SelectedValue 值和使用者選擇的Item項不一致。

但是為什麼會出現這樣奇怪的錯誤呢?
經過調查發現是因為設定了ComboBox的Sorted屬性引起的。

重新的測試代碼如下:

 

 1 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
 2         {
 3             DataRowView drv = comboBox1.SelectedItem as DataRowView;
 4             label1.Text = string.Format("Value: {0} == {1} ?", comboBox1.SelectedValue, drv.Row["ID"]);
 5         }
 6 
 7         private void frmTest_Load(object sender, EventArgs e)
 8         {
 9             DataTable dt = new DataTable();
10             dt.Columns.Add("ID", typeof(int));
11             dt.Columns.Add("Name", typeof(string));
12             dt.Rows.Add(1, "f - 1");
13             dt.Rows.Add(2, "e - 2");
14             dt.Rows.Add(3, "d - 3");
15             dt.Rows.Add(4, "c - 4");
16             dt.Rows.Add(5, "b - 5");
17             dt.Rows.Add(6, "a - 6");
18             
19             comboBox1.DataSource = dt;
20             comboBox1.ValueMember = "ID";
21             comboBox1.DisplayMember = "Name";            
22         }

 

在ComboBox裡面選擇 a -6 的話,SelectedValue 是 1 。

實際上因為設定了Sorted屬性為true。 a - 6 顯示在第一個了,也就是說 SelectedIndex 是 1.

通過測試發現, SelectedValue的值 是按照原始DataTable中Row的順序擷取的。

但是通過 SelectedItem 擷取的 ID 值是 6 ,這是正確的。所以SelectedItem的賦值還是正確的。

估計這應該是微軟的一個bug,但奇怪的是為什麼沒有兩個一起錯,而是一個錯一個對。

實驗環境:

VS2005 Vista .Net Framework 3.5 SP1 v2.0.50727.3074 。

有其它環境的朋友可以試試在其它版本的架構中是否也有同樣的bug。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.