2016-12-06 20 views
0

これは重複した質問のように見えるかもしれませんが(私はこのエラーについて他の多くの質問があります)私が持っている問題について説明します。エラーは、私が何を読んでから、追加情報:InvalidArgument = '0'の値が 'index'に無効

invList.SelectedItems[0].Text //invList is a ListView 

への呼び出しによって誘発され、この命令によって引き起こさエラーは空のリストへのアクセス試行の指標である(または配列?)リストビューで選択した項目の。しかし、私がアクセスしようとしているListViewには、命令の実行時に項目が設定されています。

方法#1:deleteItem

public bool deleteItem() 
    { 
     if (invList.SelectedItems.Count == 0) //if no item selected... 
     { 
      MessageBox.Show("Error: No item selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
      return false; 
     } 
     else 
     { 
      DialogResult dialogResult = MessageBox.Show(
       "Are you sure you want to delete item: " + invList.SelectedItems[0].Text + "?", 
       "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); 
      if (dialogResult == DialogResult.Yes) 
      { 
       for (int i = 0; i < itemRecords.Count; i++) 
       { 
        if ((itemRecords[i].id.ToString() == invList.SelectedItems[0].Text) && (itemRecords[i].practice == clinicName)) 
        { 
         itemRecords.Remove(itemRecords[i]); 
         listRefresh(); 
        } 
       } 
       return true; //return true to indicate that data has been edited 
      } 
      return false; // return false to indicate that nothing has changed 
     } 
    } 

方法#2:updateItem

public bool updateItem() 
    { 
     if (invList.SelectedItems.Count == 0) //if no item selected 
     { 
      MessageBox.Show("Error: No item selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
      return false; 
     } 
     else 
     { 
      for (int i = 0; i < itemRecords.Count; i++) 
      { 
       //if id == the id of the selected item 
       if((itemRecords[i].id.ToString() == invList.SelectedItems[0].Text) && (itemRecords[i].practice == this.Text)) 
       { 
        ItemAddition itemAddition = new ItemAddition(itemRecords, itemRecords[i], this); 
        itemAddition.ShowDialog(); 
       } 
      } 
      return true; 
     } 
    } 

listRefresh:

 public void listRefresh() 
    { 
     invList.Items.Clear(); 
     loadItems(); 
    } 

loadItemsここで私はこの命令を発行する方法は以下のとおりです。

 private void loadItems() 
    { 
     foreach (Record r in itemRecords) 
     { 
      if (r.practice == clinicName) 
       invList.Items.Add(r.ToString()); 
     } 
    } 

エラーは、最初のメソッドが呼び出されたときに呼び出されますが、2番目のメソッドが呼び出されたときには呼び出されません。この不一致が私の混乱の原因です。このエラーが最初の方法でのみ発生するいくつかの理由はありますか?

+0

listRefreshメソッドのコードを追加できますか? – Damith

+0

@Damith確かに、私はそれを追加しました。 – AustinC

+0

'for(int i = 0; i

答えて

0

アイテムを削除した後にリフレッシュ方法を移動します。アイテムを移動して再バインドすると、選択を失います。

for (int i = 0; i < itemRecords.Count; i++) 
    { 
     if ((itemRecords[i].id.ToString() == invList.SelectedItems[0].Text) && (itemRecords[i].practice == clinicName)) 
     { 
      itemRecords.Remove(itemRecords[i]); 
      //listRefresh(); 
     } 
    } 

listRefresh();     
return true; 
+0

あなたの答えを見たとき、私はちょうど私の問題の解決策を見つけました。これはまさに間違っていたものです。ご助力ありがとうございます。 – AustinC

関連する問題