Click here to Skip to main content
15,901,035 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I can not delete data because my error at 5th line and error is.

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

C#
protected void lbtnDelete_Click(object sender, EventArgs e)
   {
       var objPerson = new Person();
       GridViewRow gr = (GridViewRow)((Control)sender).NamingContainer;
       objPerson.PersonId= Convert.ToInt32(dgvPerson.DataKeys[gr.RowIndex].Values["PersonId"]);
       PersonBLL.Delete(objPerson);
       LoadPersonGrid();

   }
Posted
Updated 14-Feb-14 23:41pm
v2

Start by using the debugger: put a breakpoint on the line:
C#
objPerson.PersonId= Convert.ToInt32(dgvPerson.DataKeys[gr.RowIndex].Values["PersonId"]);
And when the application stops, start looking at the parts of it to find out exactly what indexes etc. you are dealing with.

There are two obvious candidates:
C#
dgvPerson.DataKeys[gr.RowIndex]
And
C#
Values["PersonId"]
But without your code running, we can't tell which is responsible - so it's over to you!

When you know which is causing the problem, it shouldn't be a major problem for you to work out why it's not valid - but that probably requires both the rest of your code, and your sample data, neither of which we have access to.
 
Share this answer
 
put if condition like this

GridViewRow gr = (GridViewRow)((Control)sender).NamingContainer;
if(gr.RowIndex > 0 )
{
objPerson.PersonId= Convert.ToInt32(dgvPerson.DataKeys[gr.RowIndex].Values["PersonId"]);
}
 
Share this answer
 
Comments
Patel Vinay V 15-Feb-14 6:01am    
Thanks for ans.
But problem is currently exist and give error in if condition.
Mines My RowIndex is > 0 .
Sumit_Pathak 15-Feb-14 6:26am    
show your error
Patel Vinay V 15-Feb-14 6:40am    
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Sumit_Pathak 15-Feb-14 6:47am    
it means debug pointer is going inside the if condition.then check the row index number using add watch...
Sumit_Pathak 15-Feb-14 6:49am    
what is dgvperson..? dgvperson is another gridview..am i right.?

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