Quote:
Index was out of range. Must be non-negative and less than the size of the collection.
The error occurs when you try to access an
index
of a
collection
which is not available. Just
validate
the index before accessing the item in collection.
example:
List<string> lst = new List<string>();
lst.Add("one");
lst.Add("two");
lst.Add("three");
string value = lst[4];
if (lst.Count > 4)
value = lst[4];
I hope you are getting error in the below code block
TextBox textName = (TextBox)row.Cells[0].Controls[0];
TextBox textadd = (TextBox)row.Cells[1].Controls[0];
TextBox textc = (TextBox)row.Cells[2].Controls[0];
Instead of finding the control based on the control index, you shall use
row.FindControl
to find the target element as,
TextBox textName = (TextBox)row.FindControl("YourTextBoxName");
refer these
Find Control inside gridview [
^]
Warning:
Concatenating the sql Query string is
vulnerable to
SQL Injection[
^] attacks
always use
Parameterized queries to prevent SQL Injection Attacks in SQL Server[
^]
SqlCommand cmd = new SqlCommand("update detail set name='" + textName.Text + "',address='" + textadd.Text + "',country='" + textc.Text + "'where userid='" + userid + "'", conn);
change the above code to
SqlCommand cmd = new SqlCommand("update detail set name=@name,address=@address,country=@country where userid=@userid", conn);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@address", address);
cmd.Parameters.AddWithValue("@country", country);
cmd.Parameters.AddWithValue("@userid", userid);