windows 如何使用 C#.net 替换 ListView 中一行中的列值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4767458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace value of column in a row in ListView using C#.net?
提问by HackTweaks
ID Item Code
1 Item a 1565
2 Item x **2565**
3 Item w 1245
4 Item f 1345
I have a ListView Details format like above and I want to change the value of a cell content which is in between ** mark. How can I change it such a way that it will appear in same row and without need of updating other values in a row or a table.
我有一个像上面这样的 ListView Details 格式,我想更改 ** 标记之间的单元格内容的值。如何更改它使其出现在同一行中,而无需更新行或表中的其他值。
Please Guide me in C#.net
请在 C#.net 中指导我
回答by digEmAll
Basically, it depends on how you fill your ListView
.
基本上,这取决于您如何填写ListView
.
Anyway, a code like this, should work in almost every situations:
无论如何,像这样的代码应该适用于几乎所有情况:
var idIdx = listView1.Columns["ID"].Index;
var codeIdx = listView1.Columns["Code"].Index;
foreach (ListViewItem item in listView1.Items)
{
if (item.SubItems[idIdx].Text == "2")
{
item.SubItems[codeIdx].Text = "new value...";
break;
}
}
Just a caveat:
只是一个警告:
to assure the first 2 lines of this code work, you must properly initialize your columns' Name
property, when you create them:
为确保此代码的前 2 行有效,您必须Name
在创建列时正确初始化它们的属性:
either by using the proper add overload:
通过使用正确的添加重载:
listView1.Columns.Add("ID", "ID");
or by setting it later:
或稍后设置:
var col = listView1.Columns.Add("ID");
col.Name = "ID";