【问题标题】:ArgumentOutOfRangeException when editing a record using a DataGrid使用 DataGrid 编辑记录时出现 ArgumentOutOfRangeException
【发布时间】:2014-05-10 10:27:06
【问题描述】:

美好的一天。我正在使用 asp.net C# 进行编码,并且很难使用 gridview 编辑保存在 sql server 数据库中的记录。这是我的代码

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    camConnection.ConnectionString = SqlDataSource1.ConnectionString;
    camSqlDataAdapter.SelectCommand = new SqlCommand(SqlDataSource1.SelectCommand, camConnection);
    camSqlDataAdapter.Fill(camDataSet);
    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

    TextBox pid1 = (TextBox)row.Cells[1].Controls[0];
    TextBox pname1 = (TextBox)row.Cells[2].Controls[0];
    TextBox pdesc1 = (TextBox)row.Cells[3].Controls[0];
    TextBox pquan1 = (TextBox)row.Cells[4].Controls[0];
    TextBox pprice1 = (TextBox)row.Cells[5].Controls[0];

    GridView1.EditIndex = -1;
    camConnection.Open();

    SqlCommand cmd = new System.Data.SqlClient.SqlCommand("update productInfo set ProductName='" + Convert.ToString(pname1.Text) + "', Description='" + Convert.ToString(pdesc1.Text) + "', Quantity='" + Convert.ToString(pquan1.Text) + "', Price='" + Convert.ToString(pprice1.Text) + "' where ID='" + pid1.Text + "' ", camConnection);
    cmd.ExecuteNonQuery();

    camConnection.Close();
    GridView1.DataSource = SqlDataSource1;
    GridView1.DataBind();
}

当我执行代码并在gridview中编辑记录,然后点击更新链接时,出现错误提示:

指定的参数超出了有效值的范围。 参数名称:索引

【问题讨论】:

  • 该错误发生在哪一行,可能是row.Cells[n].Controls[n]; 之一?放置断点,单步调试代码,在网络上搜索异常消息。

标签: c# asp.net sql-server-2008 gridview


【解决方案1】:

可能某些字段在您的 Gridview 中为空。 所以当你写的时候:

TextBox pid1 = (TextBox)row.Cells[1].Controls[0];

代码正在寻找一些价值。如果row.Cells[1].Controls[0] 为空,则会显示超出范围异常。 希望这会有所帮助。

【讨论】:

    【解决方案2】:

    可能某些字段在您的 Gridview 中为空。所以当你写的时候:

    TextBox pid1 = (TextBox)row.Cells[1].Controls[0]; 代码正在寻找一些价值。如果 row.Cells[1].Controls[0] 为 null,它将显示超出范围的异常。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多