首页 > 解决方案 > 如何在列表视图的特定列中添加详细信息

问题描述

我想向观察者列添加详细信息,如下图所示。我使用以下代码添加这些详细信息。但它会打印在第一列中。任何人都可以告诉我这样做。

截屏

这是我使用的代码:

private void addwatchers(string watchers)
{
   string[] row = { watchers };
   ListViewItem item = new ListViewItem(row);
   //ADD ITEMS
   listView1.Items.Add(item);
}

private void button2_Click(object sender, System.EventArgs e)
{
     string[] cwatchers = richTextBox2.Text.Split('\n');
     for (int i=0;i<cwatchers.Length;i++)
     {
         addwatchers(cwatchers[i]);
     }
}

标签: c#listview

解决方案


每次调用时,addWatchers()您都会创建一个列表视图项(列表视图中的一行)。您有多种创建此类项目的方法。您当前使用的是传递一个字符串数组,该数组表示创建每个项目的列值(按位置)。

我要做的是ListViewItem在调用者方法中创建:

for (int i = 0; i < cwatchers.Length; i++)
{
    var item = new ListViewItem(i.ToString()); //<-- arbitrarily using i as the value for the first column. You should use whatever makes sense to you.

    //TODO: add the sub item for the ID column
    item.SubItems.Add("");

    //Add in Watchers
    item.SubItems.Add(cwatchers[i]);

    //TODO: add the rest of the sub items

    //Add the item to the list view
    listView1.Items.Add(item);
}

您可以安全地摆脱该addwatchers方法,因为它只添加相应的子项。

更新

如果您在调用 addWatchers 时已经创建了项目,那么您唯一需要做的就是遍历列表视图中的项目并添加缺少的子项目。

假设您已在之前的流程中将所有项目添加到列表视图中。当您这样做时,您创建了包含两列的列表视图项。

private void button2_Click(object sender, EventArgs e)
{
    string[] cwatchers = richTextBox2Text.Split('\n');
    for (int i = 0; i < cwatchers.Length; i++)
    {
        //Get the listview item in i and add the sub item for the watchers.
        //this assumes that the list view item is created and contains two subitems so the next one to be added is the wawtchers.

        listView1.Items[i].SubItems.Add(cwatchers[i]);

        //TODO: add the rest of the sub items
    }
}

希望这可以帮助!


推荐阅读