Click here to Skip to main content
16,013,581 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I tried updating the data to database and I changed data values in GridView.
I just use below code for updating, but at the time of execution, I got this error.

------------
error:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index.

----------
code :
C#
int curview = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[e.RowIndex];
      
string id = GridView1.DataKeys[row.RowIndex].Value.ToString();
// int id=Convert.ToInt32(GridView1.DataKeys[curview].Value.ToString());
Response.Write(id);
TextBox tquantity = row.FindControl("txt_mtype") as TextBox;
string quan=tquantity.Text;
con.Open();
SqlCommand cmd3 = new SqlCommand("Update addtocart1 set quantity = @quantity where m_id = @AutoId", con);

cmd3.Parameters.AddWithValue("@quantity", quan.ToString());

cmd3.Parameters.AddWithValue("@AutoId", id);
cmd3.ExecuteNonQuery();

lblMessage.Text = "Record updated successfully !";
GridView1.EditIndex = -1;
this.BindData();
con.Close();
Posted
v2

1 solution

Please modify your code a little bit like below...
C#
// Get the "DataKey" of the row being updated.
string id = GridView1.DataKeys[e.RowIndex].Value.ToString();

// Get the "index" of Row being edited.
int curview = GridView1.EditIndex;

// Get the row being edited by "curview".
GridViewRow row = GridView1.Rows[curview];

// Find the value of TextBox by "row".
TextBox tquantity = row.FindControl("txt_mtype") as TextBox;

After this continue your coding.

Try it and let me know.

Thanks...
 
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