[英]C#: Replace Text Of Blank Items In Listview?
How would I go about about replacing the text of blank items in column 5 of my listView with the word "No"? 我如何用list“替换”替换listView第5列中空白项目的文本?
I tried this but it threw an InvalidArgument=Value of '4' is not valid for 'index'.
我尝试了这个,但它抛出了一个
InvalidArgument=Value of '4' is not valid for 'index'.
error: 错误:
foreach (ListViewItem i in listView1.Items)
{
if (i.SubItems[4].Text == " ")
{
i.SubItems[4].Text = i.SubItems[4].Text.Replace(" ", "No");
}
}
If I were you, I'd Use the debugger to figure out what's actually going on. 如果我是你,我会使用调试器来弄清楚实际发生了什么。
You can check and see what's actually in i.SubItems
, and make sure it's actually what you think it is. 您可以查看并查看
i.SubItems
的实际i.SubItems
,并确保它实际上是您认为的内容。
The only possible thing i can think of is maybe you made a typo somewhere or that i.SubItems[4]
actually just isn't valid. 我能想到的唯一可能的事情是,你可能在某个地方犯了错字或者说
i.SubItems[4]
实际上是无效的。
maybe you're iterating through some of your list items, but not all of your list items have 5 columns, or maybe some are empty. 也许你正在迭代你的一些列表项,但并非所有的列表项都有5列,或者有些列是空的。
The code provided above will get all items within ListView1.Items
and check if the sub-item of index 4
and its property Text
is equal to 上面提供的代码将获取
ListView1.Items
所有项目,并检查索引4
的子项及其属性Text
是否等于
which may result in the described error if the index exceeds the array limit. 如果索引超出数组限制,则可能导致所描述的错误。 You may avoid this by making sure that this item is not
Nothing
. 您可以通过确保此项目不是
Nothing
来避免这种情况。
Example 例
foreach (ListViewItem i in listView1.Items) //Get all items in listView1.Items
{
if (i.SubItems.Count > 3) //Continue if i.SubItems.Count is more than 3 (The array contains i.SubItems[3] which refers to an item within the 4th column (i.SubItems.Count is not an array. Therefore, it'll start with 1 instead of 0))
{
if (i.SubItems[3].Text == " ") //Continue if i.SubItems[3].Text is equal to
{
i.SubItems[3].Text = i.SubItems[3].Text.Replace(" ", "No"); //Replace with No
}
}
}
Notice : Arrays are zero-indexed which means that they start with 0 instead of 1. 注意 :数组是零索引的,这意味着它们以0而不是1开头。
Notice : If you only have 4 columns, i.SubItems.Count
would be 4 and not 3 because it's a normal int
considering that all columns are filled . 注意 :如果你只有4列,
i.SubItems.Count
将是4而不是3,因为考虑到所有列都被填充,它是一个普通的int
。
Thanks, 谢谢,
I hope you find this helpful :) 我希望这个对你有用 :)
Once you get that first error figured out, your logic for replacing the text might work better like this: 一旦你弄清楚第一个错误,你替换文本的逻辑可能会更好地工作:
if (i.SubItems != null && string.IsNullOrEmpty(i.SubItems[4].Text))
{
i.SubItems[4].Text = "No";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.