1

listView の列 5 の空白項目のテキストを「いいえ」という単語に置き換えるにはどうすればよいですか?

これを試しましたが、InvalidArgument=Value of '4' is not valid for 'index'.エラーが発生しました:

 foreach (ListViewItem i in listView1.Items)
 {
     if (i.SubItems[4].Text == " ")
     {
         i.SubItems[4].Text = i.SubItems[4].Text.Replace(" ", "No");
     }
 }
4

3 に答える 3

1

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.

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.


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.

于 2012-11-21T22:37:33.007 に答える
1

上記のコードは、その中のすべてのアイテムを取得しListView1.Items、インデックスのサブアイテム4とそのプロパティTextが等しいかどうかを確認 します。インデックスが配列の制限を超えると、前述のエラーが発生する可能性があります。このアイテムが ではないことを確認することで、これを回避できNothingます。

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

注意: 配列は 0 で始まるため、1 ではなく 0 で始まります。
注意: 列が 4 つしかない場合は、i.SubItems.Count3 ではなく 4 になりint ます

ありがとう、
これがお役に立てば幸いです:)

于 2012-11-21T22:43:05.210 に答える
1

最初のエラーを把握したら、テキストを置き換えるためのロジックは次のようにうまく機能する可能性があります。

if (i.SubItems != null && string.IsNullOrEmpty(i.SubItems[4].Text))
{
    i.SubItems[4].Text = "No";
}
于 2012-11-21T22:43:27.677 に答える