Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am getting an error called Index Out of Range while updating the grid value. Kindly have a look at the following code.
C#
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            
            string username = GridView1.DataKeys[e.RowIndex].Values["Name"].ToString();//Index was out of range. Must be non-negative and less than the size of the collection Parameter name: index (this is error)
            TextBox Remarks = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtRemarks");
            string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(connStr);
            
            con.Open();
            SqlCommand cmd = new SqlCommand("update gridsample set Remarks='" + Remarks.Text + "'where Name='" + username+"';", con);
            cmd.ExecuteNonQuery();
            con.Close();
            GridView1.EditIndex = -1;
            BindEmployeeDetails();
        }
    }
Posted
Comments
CHill60 28-Apr-14 9:33am    
You don't have "Name" in your collection of values ... have you spelled it correctly?
2012programmer 28-Apr-14 9:35am    
Yes, I have "Name" in my templatefield of gridview. It is displaying all the data, but the problem occuring while I am updating it.

1 solution

try this.

XML
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Name" >
   </asp:GridView>


Specifie the
C#
DataKeyNames="Name"


and try to get username like this
C#
string username = GridView1.DataKeys[e.RowIndex].Value.ToString();
 
Share this answer
 
v2
Comments
2012programmer 28-Apr-14 9:49am    
Thanks. This solution is working perfectly.
Bojjaiah 28-Apr-14 9:54am    
U are Welcome.

:)
2012programmer 30-Apr-14 1:20am    
I have one more question related to SQL-database sorting. I have table with 3 columns(Empcode, Department, CollegeName).Department has five different values (ECE, EEE, ..etc). Kindly let me know that how to sort department wise. For Example, I need all EEE department employees in the first then other employees of same college and then other college employees..
Bojjaiah 30-Apr-14 9:18am    
have you got an 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