如何在列表视图的特定列中添加详细信息

时间:2018-11-15 18:54:02

标签: c# listview

我想像下面的图像一样向观察者列添加细节。我使用以下代码添加这些细节。但是它打印在第一列中。有人可以告诉我这样做吗。

screenshot

这是我使用的代码:

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]);
     }
}

1 个答案:

答案 0 :(得分:0)

每次调用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时已经创建了项目,那么唯一要做的就是遍历列表视图中的项目并添加缺少的子项目。

假设您在上一个过程中将所有项目添加到了列表视图。然后,您创建了具有两列的listview项。

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
    }
}

希望这会有所帮助!