指数超出范围.必须为非负且小于集合参数 name:index 的大小 [英] Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

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

问题描述

我正在尝试将数据一行一行地添加到数据网格视图中,这是我的代码,它说:

I'm trying to add data as one by one row to a datagridview here is my code and it says:

"索引超出范围.必须为非负且小于集合的大小参数名称:索引"

"Index was out of range. Must be non-negative and less than the size of the collection parameter name:index"

这是什么意思?我的代码有什么问题?

What does this mean? What is the problem in my code?

String Sqlstr2 = "select ItemName from Item where ItemID = '" + tbItemID.Text + "'";
db.DataRead(Sqlstr2);
string ItemName = db.dr["ItemName"].ToString(); 

DataGridView dataGridView1 = new DataGridView();

dataGridView1.Columns[0].Name = "ItemID";
dataGridView1.Columns[1].Name = "ItemName";
dataGridView1.Columns[2].Name = "Qty";
dataGridView1.Columns[3].Name = "UnitPrice";
dataGridView1.Columns[4].Name = "Amount";

string firstColum = tbItemID.Text;
string secondColum = ItemName;
string thirdColum = tbQuantity.Text;
string fourthColum = Convert.ToString(UnitPrice);
string fifthColum = Convert.ToString(sum);

string[] row = new string[]{ firstColum, secondColum, thirdColum, fourthColum, fifthColum };
dataGridView1.Rows.Add(row);

推荐答案

您没有向 DataGridView

DataGridView dataGridView1 = new DataGridView();//Create new grid

dataGridView1.Columns[0].Name = "ItemID";// refer to column which is not there 

现在清楚为什么会出现异常了吗?

Is it clear now why you get an exception?

在使用列修复错误之前添加此行

Add this line before you use columns to fix the error

dataGridView1.ColumnCount = 5;

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

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