Click here to Skip to main content
15,920,217 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
       int sr = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
       b.srno = sr;
       GridView1.EditIndex = -1;

What I have tried:

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

Whenever i click on Delete (for Given CODE) then Above Error is display.
Kindly help me out....
Updated 6-Oct-16 3:41am

First, you need to check which line the error is coming from. There are three possibilities here: lines 1, 3 & 5. Since 3 and 5 are function calls I cannot say from this code if they are generating the error or not.

If it is the first line indeed from where the exception is thrown, please check if you are rebinding the grid before RowDeleting event fires and whether the row being deleted is removed from data source causing the exception.

To check exactly which line of code is causing the exception – If you are running the code in debug mode from Visual Studio you will be getting an error message in a popup like this: Check below link

Click on “View Detail…” link (as circled in the screenshot). Expand the message and look at StackTrace (I usually copy it to notepad so it is more readable).

Check below link

Here you will see list the of functions from top to bottom of the stack. The ones which have line numbers are of interest to us. The first line number (top of the stack) is the culprit in our code. In the example screen show, I attached, the exception is caused by our code at line 55 in WebForm1.aspx.
Happy debugging!
Share this answer
The error is pretty self explanatory:
Index was out of range. Must be non-negative and less than the size of the collection.

In that code you are using just one index:
int sr = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);

So e.RowIndex is either negative or bigger than the DataKeys collection.
So check that you have the DataKeyNames property set, and use the debugger to find out what the index value is, and how big the collection is.

We can't do that for you: we can't run your code, and don't have access to your data!
Share this answer

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