【问题标题】:adding items to columns/rows in listview using foreach使用 foreach 将项目添加到列表视图中的列/行
【发布时间】:2012-07-09 08:10:35
【问题描述】:

我进入了学习 c# 的第 5 天,我正在尝试弄清楚如何使用 foreach 循环填充/重新填充包含 10 行和 12 列的 ListView 控件。我已经用 C 编写了我想要的功能。

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 循环来做到这一点,不是吗?

【问题讨论】:

  • 我的问题是:一定有办法在 C# 中使用 for 或 foreach 循环来做到这一点,不是吗?

标签: c# listview foreach itemscontrol


【解决方案1】:

我不确定我是否理解正确,但我认为这是你需要的......

实际上,这取决于您用来填充ListViewDataSource。 像这样的东西(我在这里使用Dictioanry 作为数据源)-

        // 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...

希望对你有帮助!

【讨论】:

    【解决方案2】:

    您执行此操作几乎与在 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);
    }
    

    如果不看你的集合是什么样子,很难提供一个真实的例子,但是对于一个数组数组,这将起作用。

    【讨论】:

      猜你喜欢
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      相关资源
      最近更新 更多