索引超出范围。必须是非负数且小于集合的大小 [英] Index was out of range. Must be non-negative and less than the size of the collection

查看:177
本文介绍了索引超出范围。必须是非负数且小于集合的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误是:索引超出范围。必须是非负数且小于集合的大小。

Error is: Index was out of range. Must be non-negative and less than the size of the collection.

方案:我有一个桌面应用程序加载XML文件并在Grid中显示数据。现在,我想插入另一个文件,并希望在两个文件中附加数据。但是,当我尝试合并数据(我的意思是添加行到DataTable,它有一行显然打开的文件)...我收到这个错误。

Scenario: I have a desktop application which loads XML Files and display the data in Grid. Now, I want to insert another file and want to append the data in both files. But, when I try to merge the data (I mean add the rows to DataTable which has rows of perviously opened file)...I am getting this error.

if (strPreviousFile != "")   
{  
  dgvBooksDetails.DataSource = dtBooks;   
  int intCurrentRows = dgvBooksDetails.Rows.Count;   
  intBooksCounter = intBooksCounter + intCurrentRows;   
  for (int c = intCurrentRows; c < intBooksCounter; c++)  
  {   
    Book objBook = new Book();   
    objBook.ID = BookID[c];   
    objBook.Title = BookTitle[c];  
    objBook.Author = BookAuthor[c];  
    objBook.Genre = BookGenre[c];  
    objBook.Price = Double.Parse(BookPrice[c]);  
    objBook.PublishDate = DateTime.Parse(BookPublish_Date[c]);  
    objBook.Description = BookDescription[c];  
    dtBooks.Rows.Add(objBook.ID, objBook.Title, objBook.Author, objBook.Genre,
                     objBook.Price, objBook.PublishDate, objBook.Description);   
  }
}

我如何克服这个错误?

推荐答案

造成麻烦的一线是:

int intCurrentRows = dgvBooksDetails.Rows.Count;

将此值作为循环开始。但是,行集合从0到 Count-1 ,因此使用 Count 访问rows集合的值导致索引超出边界错误。

You take this value as start for your loop. However, the rows collection counts from 0 to Count-1, so using Count to access a value of the rows collection causes an index out of bounds error.

另一件事: BookTitle BookAuthor 等也从0索引到 Count-1 (或 Length-1 如果它们是数组)。我不知道你告诉我们什么,但你确定这些集合可以通过索引的方式访问吗?我的意思是说,它只是包含要添加的项目,因此需要从0到X索引,而不是现有项目的数量现有项目数量+新项目数量(这是您在代码中所做的)?

Another thing: BookTitle, BookAuthor etc. are also indexed from 0 to Count-1 (or Length-1 if they are arrays). I'm not sure from what you've told us, but are you sure that these collections can be accessed by index the way you do? I mean, could it be they only contains the items to be added and thus need to be indexed from 0 to X instead of number of existing items to number of existing items + number of new items (that's what you do in your code)?

这篇关于索引超出范围。必须是非负数且小于集合的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆