使自己成爲一個密碼管理器,我遇到了一段代碼的問題。應該會發生的事情是應用程序打開一個xml文件,然後用該xml文檔(帳戶)中包含的項目填充listview。在列表視圖上右鍵單擊可爲各種選項提供上下文菜單,所有這些都可單獨工作。然而,打開XML文檔,然後從列表視圖中的一個帳戶,然後嘗試添加其他帳戶後,它會引發以下:C#:如何解決這個ArgumentOutofRangeException?
ArgumentOutOfRangeException unhandled.
InvalidArgument=Value of '4' is not valid for 'index'.
Parameter name: index
我假設怎麼回事錯誤是,當我刪除來自listview的帳戶,我搞亂了在應用程序啓動時xml文檔中的每個項目遞增的索引變量的計數。不確定在不破壞其他代碼部分的情況下解決這個問題的最佳方法。我正在考慮通過計算listView中有多少項目總數來刪除帳戶後重置'index'的值,但不確定最佳值是多少。這是xml打開時代碼的樣子。
private void openPasswordFileToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Xml.XmlDocument loadDoc = new System.Xml.XmlDocument();
try
{
loadDoc.Load(Application.StartupPath + "\\database.xml");
}
catch (System.IO.FileNotFoundException)
{
MessageBox.Show("Password Database does not exist!");
}
foreach (System.Xml.XmlNode node in loadDoc.SelectNodes("/Database/Account"))
{
lvItem = listView1.Items.Insert(index, node.Attributes["Description"].InnerText); ;
lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, node.Attributes["Username"].InnerText)); ;
lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, node.Attributes["Password"].InnerText)); ;
index += 1;
}
}
最後去除帳戶段:直到執行下列順序
private void removeSelectedAccountToolStripMenuItem_Click(object sender, EventArgs e)
{
listView1.Items.Remove(listView1.SelectedItems[0]);
}
再次一切正常:開立的賬戶文件 - >刪除帳號 - >其他帳戶加入。此時拋出異常,並且新帳戶永遠不會添加到列表視圖中。
這裏是例外的細節。這是'堆棧轉儲'?
System.ArgumentOutOfRangeException was unhandled Message=InvalidArgument=Value of '3' is not valid for 'index'. Parameter name: index Source=System.Windows.Forms ParamName=index StackTrace: at System.Windows.Forms.ListView.ListViewItemCollection.Insert(Int32 index, ListViewItem item) at System.Windows.Forms.ListView.ListViewItemCollection.Insert(Int32 index, String text) at PassKeeper.Form1.addAccountToolStripMenuItem_Click(Object sender, EventArgs e) in C:\Users\Hamann\documents\visual studio 2010\Projects\PassMan\PassMan\Form1.cs:line 35
我將交易大部分代碼,用於拋出實際的線和/或堆棧。 – 2011-05-22 19:59:36