2012-07-09 85 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); 
} 

很难提供一个真实的例子,没有看到你的收藏是什么样子,但对于数组数组这将工作。

相关问题