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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With