【发布时间】:2013-04-10 14:34:45
【问题描述】:
又一次被这个列表视图对象弄糊涂了。当我尝试从 Windows 表单中的列表视图中检索选定的列表视图项时,我的代码会出现“下标越界”错误。使用 VS add watch 命令,我看到以下内容当我查看 listview 对象的手表时,我看到以下内容
this.SearchResults {System.Windows.Forms.ListView, Items.Count: 52, Items[0]: ListViewItem: {0}} System.Windows.Forms.ListView
所以我看到 52 的计数是正确的,当程序运行时,我可以从集合中选择一行。例如,假设我从集合中挑选了第 5 个项目。 Watch 将返回以下内容
this.SearchResults.SelectedIndices[0] 5 int
因此,对于索引,我只想将 listviewitem 传递给另一个对象以进行进一步处理。当我尝试这个时,我得到一个运行时错误
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll
Additional information: InvalidArgument=Value of '5' is not valid for 'index'.
这怎么可能?我有 52 个项目,代码表现得好像列表视图是空的。我曾尝试对索引进行硬编码,但也没有用。
我的这个表单的构造函数的代码列表视图在下面
public ResultsDisplay(List<MATS_Doc> foundDocs)
{
InitializeComponent();
this.CenterToScreen();
this.SearchResults.Columns.Add("Title");
this.SearchResults.Columns.Add("Stuff");
foreach (MATS_Doc doc in foundDocs)
{
// retrieve coresponding document
// create new ListViewItem
ListViewItem searchResults = new ListViewItem(doc.Id.ToString());
searchResults.SubItems.Add(doc.Title);
searchResults.SubItems.Add(doc.Stuff);
// add the listviewitem to a new row of the ListView control
this.SearchResults.Items.Add(searchResults); //show Text1 in column1, Text2 in col2
}
foreach (ColumnHeader column in this.SearchResults.Columns)
{
column.Width = -2;
}
this.Show();
}
更新
下面是抛出异常的代码。列表视图的形式相同
if (scoredListing == null)
{
DocumentView showdoc = new DocumentView(this.SearchResults.SelectedItems[this.SearchResults.SelectedIndices[0]]);
showdoc.ShowDialog();
}
【问题讨论】:
-
你能给我们更多的代码来看看这个 List 是如何初始化的,或者 Property 的样子吗?
-
我不明白你说你选择第 5 项的那一行...看起来你试图选择第 5 个 selected 项,而不是项。跨度>
-
我很想知道您“粘贴”列表视图项的代码
-
请发布引发异常的代码。单独的异常并不能帮助我们检测到任何东西。或者,GlaDOS 会怎么说:它不能帮助我们,帮助你,帮助我们,帮助我们所有人 ;)
-
我用违规行更新了帖子。我正在启动另一个表单,并尝试使用 SelectedItems 字段传递 listviewitem。
标签: c# listview runtime-error listviewitem