且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-04-12 22:17:37

造成麻烦的一线是:

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)?