Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index was out of range. Must be non-negative and less than the size of the collection parameter 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); 
like image 541
user2566013 Avatar asked Oct 03 '13 14:10

user2566013


1 Answers

The error says "The index is out of range". That means you were trying to index an object with a value that was not valid. If you have two books, and I ask you to give me your third book, you will look at me funny. This is the computer looking at you funny. You said - "create a collection". So it did. But initially the collection is empty: not only is there nothing in it - it has no space to hold anything. "It has no hands".

Then you said "the first element of the collection is now 'ItemID'". And the computer says "I never was asked to create space for a 'first item'." I have no hands to hold this item you are giving me.

In terms of your code, you created a view, but never specified the size. You need a

dataGridView1.ColumnCount = 5; 

Before trying to access any columns. Modify

DataGridView dataGridView1 = new DataGridView();  dataGridView1.Columns[0].Name = "ItemID"; 

to

DataGridView dataGridView1 = new DataGridView(); dataGridView1.ColumnCount = 5; dataGridView1.Columns[0].Name = "ItemID"; 

See http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columncount.aspx

like image 152
Floris Avatar answered Oct 17 '22 05:10

Floris