Click here to Skip to main content
14,924,336 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

Can anyone know this.

how to solve index was out of range. must be non-negative and less than the size of
the collection?

code is:

protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
       int id = GridView1.EditIndex;
       GridViewRow rows = GridView1.Rows[e.RowIndex];
       int row = Convert.ToInt32(GridView1.DataKeys[id].Value.ToString());
       if (((TextBox)rows.FindControl("txtname") != null) && ((TextBox)rows.FindControl("txtaddress") != null))
           TextBox txtname = (TextBox)rows.FindControl("txtname");
           TextBox txtaddress = (TextBox)rows.FindControl("txtaddress");
           SqlCommand cmd = new SqlCommand("update employee set emp_name='" + txtname.Text + "',emp_address='" + txtaddr.Text + "' where emp_id='" + id + "", con);
           GridView1.EditIndex = -1;
Updated 20-Jul-12 5:09am
Rajesh Varma Buddaraju 20-Jul-12 14:31pm
This is a common issue. Debug the code then u will find it or let us know in which line u r getting this issue!

Without the actual code to work from, we can't be that precise.

But the error is pretty clear: You are accessing a collection of some form (list, array or other) using an index which is either negative, or larger than the index of the last value in the collection.

For example, if you have a list or an array that you are accessing in a loop, the loop counter must be less than the items count:
for (int i = 0; i < myCollection.Length; i++)
Will be fine, but
for (int i = 1; i <= myCollection.Length; i++)
You can check if your index is in the range :
string[] arr = new string[3];
if(index < arr.Length) // check if in range
   string s = arr[index];
int id = GridView1.EditIndex;

this might be the issue , and as per my knowledge,GridView1.EditIndex;can not be emp_id.

if GridView1.EditIndex return 1 or 2 , there is a possibility that you have datakey, but if you are editing some 20th row and you dont have 20 different datakeys types.

Try to use the code
int row = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
to get your emp id.
int row = Convert.ToInt32(GridView1.DataKeys[id].Value.ToString());
This line might be throwing the error.
Here id = GridView1.EditIndex, represets an index.
In (GridView1.DataKeys[id].Value.ToString(), you are trying get value from GridView1.DataKeys at index id. But there might not be any key for this index.

Check for that.

Happy Coding :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900