Click here to Skip to main content
15,915,164 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
here is my code;
C#
protected void Del_Button_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in GD1.Rows)
        {
            CheckBox chk = (CheckBox)row.FindControl("Chkid");
            if (chk.Checked)
            {
             int dr = Convert.ToInt32(GD1.DataKeys[row.RowIndex].Values[0]);

            SqlParameter[] param_add_user = new SqlParameter[] 
            {
               new SqlParameter("@Sno",dr)
            };
                SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "Del", null);
            }
        }
        BindData();
    }


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

1 solution

The error could be in the line
C#
int dr = Convert.ToInt32(GD1.DataKeys[row.RowIndex].Values[0]);

because, the foreach loop will not execute if the GD1.Rows is empty. If null is returned as chk , then Null Reference exception would have been thrown. That means the execution may be continuing upto the above line and there may be error either in row.RowIndex or .Values[0]

Put a break point just after this line and when code execution stops there, check the value of row.RowIndex and .Values[0]

I think it may be helpful.
 
Share this answer
 
Comments
pck.ns 28-Apr-12 0:24am    
thanx for ur response, but still i am not getting it in right way. i am new in this field
VJ Reddy 28-Apr-12 0:39am    
When you checked by placing a break point at the line specified above, what was the value of row.RowIndex?
pck.ns 28-Apr-12 0:57am    
its value is 10
VJ Reddy 28-Apr-12 1:31am    
Then the reason could be the DataKeyNames property of GridView, explained here

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeynames.aspx
might not have been set, because as given under remarks at

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeys.aspx

When the DataKeyNames property is set, the GridView control automatically creates a DataKey object for each row in the control. The DataKey object contains the values of the field or fields specified in the DataKeyNames property. The DataKey objects are then added to the control's DataKeys collection. Use the DataKeys property to retrieve the DataKey object for a specific data row in the GridView control.

So, try by assigning the DataKeyNames property
pck.ns 28-Apr-12 1:59am    
i have used datakeynames property as---Sno
but now it showing error:Procedure or function 'Del' expects parameter '@Sno', which was not supplied.

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