且构网

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

数据网格视图索引错误。指数超出范围。必须是非负且小于集合的大小。

更新时间:2022-06-13 06:14:53

当你试图访问不包含记录的网格视图数据时会发生这种情况。

无论你在哪里使用网格,检查它是否有行。

对于ex :您正在访问for循环中的网格单元格。所以在for循环之前使用这样的条件。



This is happening when u r trying to access the grid view data which contains no records.
Wherever you are using the grid, check if it is having rows.
For ex: You are accessing the grid cells in for loop. so before for loop use a condition like this.

if(DataGridViewCell.Rows.Count >0)
{
For()
}


这意味着什么?在我的代码中有任何问题

这意味着您正在访问集合中不存在的位置或索引。



要查找这一点,确保您的Gridview有5列,因为您正在使用它的第5列。



dataGridView1.Columns [4] .Name =Amount;

这是显示数组元素的图像。因此,如果您的gridview有较少的列,然后是您访问它的(index + 1),则会出现此异常。



在此处输入图像描述
what this means ? is there any problem in my code
It means that you are accessing a location or index which is not present in collection.

To find this, Make sure your Gridview has 5 columns as you are using it's 5th column by this line

dataGridView1.Columns[4].Name = "Amount";
Here is the image which shows the elements of an array. So if your gridview has less column then the (index + 1) by which you are accessing it, then this exception arises.

enter image description here


这是你的代码:

This is your code:
while (sqlReader.Read())
              {
                  object[] row = { sqlReader[0], sqlReader[1], sqlReader[2], sqlReader[3], sqlReader[4], sqlReader[5], sqlReader[6], sqlReader[7] };
                  dataGridView1.Rows.Add(row);
              }





请在条件允许的情况下删除。



输入:

datagridview1.datasource = sqlreader;

然后编辑网格模板以仅显示选定的列



Please Remove while condition.

enter:
datagridview1.datasource=sqlreader;
then edit grid template to show only selected columns