• Register
0 votes
37 views

Problem :

 

I want to add the data as one by one row to my datagridview.  But I am facing the following error:

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

Why am I facing this error ? Do I need to make anychanges in my following code:

String Sqlstr = "select ItemName from Item where ItemID = '" + tbItemID.Text + "'";
db.DataRead(Sqlstr);
string ItemName = db.dr["ItemName"].ToString(); 
DataGridView myDataGridView = new DataGridView();
myDataGridView.Columns[0].Name = "ItemID";
myDataGridView.Columns[1].Name = "ItemName";
myDataGridView.Columns[2].Name = "Qty";
myDataGridView.Columns[3].Name = "UnitPrice";
myDataGridView.Columns[4].Name = "Amount";
string ColumOne = tbItemID.Text;
string ColumTwo = ItemName;
string ColumThree = tbQuantity.Text;
string ColumFour = Convert.ToString(UnitPrice);
string ColumFive = Convert.ToString(sum);
string[] row = new string[]{ ColumOne, ColumTwo, ColumThree, ColumFour, ColumFive };
myDataGridView.Rows.Add(row);
6 5 3
7,540 points

1 Answer

0 votes

Solution :

Your error is saying "The index is out of range". It means you wanted to index an object with a value that was invalid. If you have five Chairs, and I ask you to give me the sixth Chair, then you will look at me in funny manner. Same is your computer looking at you in funny way. You asked him - "create a collection" So it created one for you but initially the collection is empty: and there is nothing in it  and no space to hold anything. "It has no hands".

After that you told him "Now the first element of the collection is the 'ItemID'". But the computer says "You never asked me to create space for a 'first item'." I have no hands to grab this item which you are giving me.

So in terms of your code, you just created the view, but never specified its size. You need the

myDataGridView.ColumnCount = 5;

Before even trying to access the columns. Pleaase update

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

to the below code:

DataGridView myDataGridView = new DataGridView();
myDataGridView.ColumnCount = 5;
myDataGridView.Columns[0].Name = "ItemID";
9 7 4
38,600 points

Related questions

0 votes
1 answer 56 views
56 views
Problem : I am facing this Kind of Error like:: Specified argument was out of the range of valid values.Parameter name: site While Debugging any of the Project. I have also tried after Reinstalling the Visual ... +9873912 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
asked Jan 20 jwilliam 3.9k points
0 votes
1 answer 73 views
73 views
Problem : I am getting bellow error related to datetime the conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
asked Nov 7, 2019 peterlaw 6.9k points
0 votes
1 answer 17 views