Click here to Skip to main content
16,004,806 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
private void SaveCheckBoxState()
    {
        ArrayList employeeIDs = new ArrayList();
        int index = -1 ;

        foreach (GridViewRow row in GridView1.Rows)
        {
            **index = (int)GridView1.DataKeys[row.RowIndex].Value;**
            bool result = ((CheckBox)row.FindControl("chkcheck")).Checked;

            if (Session["Selected"] != null)
            {
                employeeIDs = (ArrayList)Session["Selected"];
            }

            if (result)
            {
                if (!employeeIDs.Contains(index))
                {
                    employeeIDs.Add(index);
                }
            }
            else
            {
                employeeIDs.Remove(index);
            }
        }
        if (employeeIDs != null && employeeIDs.Count > 0)
        {
            Session["Selected"] = employeeIDs;
        }
    }

C#
i got this error at runtime plz try to solve this Error: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index


What I have tried:

i try int index=0;
but this also not work
Posted
Updated 18-May-16 14:35pm

This is probably going to depend on your data, which we don't have access to.
Start start by using the debugger, and set a breakpoint on the line:
C#
index = (int)GridView1.DataKeys[row.RowIndex].Value;
When it hits the breakpoint, execution should stop, and let you look at what is going on.
At at the row, and it's RowIndex property, then check that against the DataKeys collection.
At a guess, it's empty, so you get the error.
A quick look at the documentation GridView.DataKeys Property (System.Web.UI.WebControls)[^] says it might be the setting of the DataKeyNames property - but you need to look at the data while it's running to confirm exactly what you have.
 
Share this answer
 
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

C#
int index = -1 ;

is certainly the first problem.
Check that GridView1 is same size as employeeIDs
 
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