2014-08-28 26 views
0

我會參考這個鏈接。 How do I make items in the ListBox as headers of GridView排序列表框項目在gridview中創建標題

給出上面的鏈接具有如何使列表框項目成爲gridview的headertext的功能。 。我的問題是。如果我有一個2列表框。首先是由數字組成,其次是名稱/單詞。我如何根據listbox1上的數字對第二個列表框進行排序,然後使輸出成爲gridview的標題?

LBox1 LBox2

3 AAA

2 DDD

1 EEE

5 BBB

4 CCC

GridView的頭應該是

EEE DDD AAA CCC BBB。 很高興如果你能提供示例代碼。謝謝!

回答

0

首先你必須創建一個SortedDictionary。這個碰撞會根據鍵自動排序。

SortedDictionary<string, string> values = new SortedDictionary<string, string>(); 

,然後用你的兩個列表

for (int i = 0; i < ListBoxnumbers.Items.Count; i++) 
     { 
      values.Add(ListBoxnumbers.Items[i].ToString(), ListBox1.Items[i].ToString()); 
     } 

之後另一個循環將填補頭

foreach (KeyValuePair<string,string> item in values) 
     { 
      dt.Columns.Add(item.Value, System.Type.GetType("System.String")); 
     } 
+0

有一點問題填寫數據,標題不正確,如果排序ListBox1中得到(1,2,14,3,16,5,4)(1,14,16,2,3,4,5)。 。 – BeginnerProgrammer 2014-08-28 02:21:53

+0

現在就工作。將foreach(KeyValuePair 項中的值)更改爲foreach(值中的KeyValuePair 項)。和值.Add(ListBoxnumbers.Items [i] .ToString()to values.Add(Convert.ToInt16(ListBoxnumbers.Items [i] .ToString())。和其他 – BeginnerProgrammer 2014-08-28 02:26:42