C# 更新SQL Server前端应用程序中的字段时出错
我正在做一个几乎完成的应用程序,除了我的一页 页面上有一个gridview,它显示了一个数据库中的数据,该数据库工作正常,问题是当用户试图更新信息时,它抛出了错误 这是我的代码-有人能看到我做错了什么,以及我如何解决这个问题吗C# 更新SQL Server前端应用程序中的字段时出错,c#,sql,asp.net,web-applications,C#,Sql,Asp.net,Web Applications,我正在做一个几乎完成的应用程序,除了我的一页 页面上有一个gridview,它显示了一个数据库中的数据,该数据库工作正常,问题是当用户试图更新信息时,它抛出了错误 这是我的代码-有人能看到我做错了什么,以及我如何解决这个问题吗 protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = GridView1.Rows[e.RowIndex]; int Id =
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();
}
显示的错误是:
索引超出范围。必须为非负数且小于集合的大小。参数名称:索引 异常详细信息:System.ArgumentOutOfRange异常:索引超出范围。必须为非负数且小于集合的大小。
参数名称:索引 源错误: 第61行:{
第62行:GridViewRow行=GridView1.Rows[e.RowIndex];
第63行:int Id=Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
第64行:int Period_Id=Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
第65行:int Evo_StockLink=Convert.ToInt32(GridView1.DataKeys[e.RowIndex]。值[0])
在aspx中,确保您具有DataKeyNames=“Id”,您还可以使用数据键传递所有字段,这将更新整个数据库到该值。如果您不告诉我们错误是什么,我们如何帮助您?另外,不要使用!调试此操作时,该行代码上的哪些索引超出范围?有两个数组引用,
Datakeys[e.RowIndex]
和value[0]
。其中一个超出了范围。请调试并找出哪一个。代码假定某个内容存在,但实际不存在,在尝试使用该数据之前,您需要检查数据是否存在。出于其他原因,您已投票关闭该问题,但也重复了以下内容: