c# - 如何在列表视图的特定列中添加详细信息
问题描述
我想向观察者列添加详细信息,如下图所示。我使用以下代码添加这些详细信息。但它会打印在第一列中。任何人都可以告诉我这样做。
这是我使用的代码:
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]);
}
}
解决方案
每次调用时,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
}
}
希望这可以帮助!
推荐阅读
- python - 如何更改图像特定区域的颜色?
- vue.js - Vue 编译器无法解析“vue”
- asynchronous - 如何在异步函数中使用谓词?
- sql - MS Access - VBA - 克隆表
- python - 如果用户尝试除以 10/'dog',我试图防止出现错误。即使在使用异常后我仍然得到错误
- spring-boot-test - 如何在 Spring Boot 单元测试的 WebMvcTest 中检查预期的控制器是否加载
- javascript - 需要在全局范围内还是在本地范围内?
- javascript - 动态加速后从同一点恢复css动画
- google-colaboratory - Google Colab 中的 OpenAI 健身房渲染()
- regex - 如何在perl的if语句中捕获由逻辑AND分隔的多个正则表达式组?