I am working on an application which is nearly complete except for my one page.
On the page is a gridview which is showing data from a database which works, the problem is when the user tries to update the information it is throwing out errors.
This is my code - can someone see what I am doing wrong and how I can solve this problem?
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
int Period_Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
int Evo_StockLink = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string Evo_ItemCode = (row.Cells[4].Controls[0] as TextBox).Text;
string Evo_Description = (row.Cells[5].Controls[0] as TextBox).Text;
float UnitRate = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
float MinRate = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
float RateBeforeSevenDays = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
float RateAfterSevenDays = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("UPDATE rates SET Period_Id = @Period_Id, Evo_StockLink = @Evo_StockLink, Evo_ItemCode = @Evo_ItemCode, Evo_Description = @Evo_Description, MinRate = @MinRate, RateBeforeSevenDays = @RateBeforeSevenDays, RateAfterSevenDays = @RateAfterSevenDays WHERE Id = @Id"))
{
cmd.Parameters.AddWithValue("@Id", Id);
cmd.Parameters.AddWithValue("@Period_Id", Period_Id);
cmd.Parameters.AddWithValue("@Evo_StockLink", Evo_StockLink);
cmd.Parameters.AddWithValue("@Evo_ItemCode", Evo_ItemCode);
cmd.Parameters.AddWithValue("@Evo_Description", Evo_Description);
cmd.Parameters.AddWithValue("@UnitRate", UnitRate);
cmd.Parameters.AddWithValue("@MinRate", MinRate);
cmd.Parameters.AddWithValue("@RateBeforeSevenDays", RateBeforeSevenDays);
cmd.Parameters.AddWithValue("@RateAfterSevenDays", RateAfterSevenDays);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1;
this.BindGrid();
}
The error shown is :
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: indexException Details: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: indexSource Error:
Line 61: {
Line 62: GridViewRow row = GridView1.Rows[e.RowIndex];
Line 63: int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
Line 64: int Period_Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
Line 65: int Evo_StockLink = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);