2014-08-28 57 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