Click here to Skip to main content
15,896,111 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
I got this error i am writing this code
the error will comes if condition int userid


C#
foreach (GridViewRow gvrow in gvuserdetails1.Rows)
       {
           //Finiding checkbox control in gridview for particular row
           CheckBox chkdelete = (CheckBox)gvrow.FindControl("chkdelete");
           //Condition to check checkbox selected or not
           if (chkdelete.Checked)
           {
               //Getting UserId of particular row using datakey value
               int usrid = Convert.ToInt32(gvuserdetails1.DataKeys[gvrow.RowIndex].Value);
               objusers.DeleteParameters["UserId"].DefaultValue = usrid.ToString();
               objusers.Delete();
           }
Posted
Updated 9-Jun-13 19:40pm
v2
Comments
Rockstar_ 10-Jun-13 1:44am    
You are getting error at this line : int usrid = Convert.ToInt32(gvuserdetails1.DataKeys[gvrow.RowIndex].Value);

So check with break point each loop for the value of gvrow.RowIndex , may be getting error at last loop,try keeping int usrid = Convert.ToInt32(gvuserdetails1.DataKeys[gvrow.RowIndex-1].Value);
Francisco T. Chavez 10-Jun-13 1:46am    
Is it the code for getting use user id that's giving you the error or the code for deleting that row?

The error means what it says. If you were to use your debugger, you could see what was going on.

gvuserdetails1.DataKeys has less or equal number of keys, than gvrow.RowIndex, that's why you are getting this exception.

Just make sure that "DataKeyNames" property is set with any field id(i.e UserID etc). When you have set DataKeyNames property, Gridview control automatically creates DataKey object for each row.


--Amit
 
Share this answer
 
Comments
Gujula Ravindra Reddy 10-Jun-13 2:14am    
Thanku sir .......
Try like :

C#
CheckBox chk = (CheckBox)gvrow.Cells[index value of checkbox column].FindControl("chkdelete");


and follow the other answer also.
 
Share this answer
 
v3

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