2012-07-09 128 views
1

我到了學習c#的第5天,並且試圖找出如何使用foreach循環來填充/重新填充包含10行和12列的ListView控件。我已經在C編碼,我的功能後使用foreach在列表視圖中添加項目到列/行

void listPopulate(int *listValues[], int numberOfColumns, int numberOfRows) 
{ 
    char table[100][50]; 
    for (int columnNumber = 0; columnNumber < numberOfColumns; ++columnNumber) 
    { 
     for (int rowNumber = 0; rowNumber < numberOfRows; ++rowNumber) 
     { 
      sprintf(&table[columnNumber][rowNumber], "%d", listValues[columnNumber][rowNumber]); 
      // ... 
     } 
    } 
} 

這是我迄今想通了:

public void listView1_Populate() 
{ 

    ListViewItem item1 = new ListViewItem("value1"); 
    item1.SubItems.Add("value1a"); 
    item1.SubItems.Add("value1b"); 

    ListViewItem item2 = new ListViewItem("value2"); 
    item2.SubItems.Add("value2a"); 
    item2.SubItems.Add("value2b"); 

    ListViewItem item3 = new ListViewItem("value3"); 
    item3.SubItems.Add("value3a"); 
    item3.SubItems.Add("value3b"); 
    .... 

    listView1.Items.AddRange(new ListViewItem[] { item1, item2, item3 }); 
} 

我假設我必須做的創造在單獨的步驟中列出項目。所以我的問題是:必須有一種方法在C#中使用for或foreach循環來做到這一點,不是嗎?

+0

什麼問題? – 2012-07-09 09:10:59

+0

我的問題是:必須有一種方法在C#中使用for或foreach循環來做到這一點,不是嗎? – PaeneInsula 2012-07-09 09:47:42

回答

1

我不知道如果我理解正確的你,但這裏是我認爲你需要什麼...

其實這取決於你DataSource您正在使用,填補了ListView。 像這樣的東西(我使用Dictioanry作爲一個DataSource這裏) -

 // Dictinary DataSource containing data to be filled in the ListView 
     Dictionary<string, List<string>> Values = new Dictionary<string, List<string>>() 
     { 
      { "val1", new List<string>(){ "val1a", "val1b" } }, 
      { "val2", new List<string>(){ "val2a", "val2b" } }, 
      { "val3", new List<string>(){ "val3a", "val3b" } } 
     }; 

     // ListView to be filled with the Data 
     ListView listView = new ListView(); 

     // Iterate through Dictionary and fill up the ListView 
     foreach (string key in Values.Keys) 
     { 
      // Fill item 
      ListViewItem item = new ListViewItem(key); 

      // Fill Sub Items 
      List<string> list = Values[key]; 
      item.SubItems.AddRange(list.ToArray<string>()); 

      // Add to the ListView 
      listView.Items.Add(item); 
     } 

我簡單的理解代碼,因爲有幾種方式通過Dictionary迭代...

希望它可以幫助!

1

你這樣做幾乎完全一樣,在通過收集C.只是環......

int i = 0; 
foreach (var column in listValues) 
{ 
    var item = new ListViewItem("column " + i++); 
    foreach (var row in column) 
    { 
     item.SubItems.Add(row); 
    }   
    listView1.Items.Add(item); 
} 

很難提供一個真實的例子,沒有看到你的收藏是什麼樣子,但對於數組數組這將工作。