protected void gd_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtAuthor;
TextBox txtBook;
dt = new DataTable();
dt=(DataTable)ViewState["dt"];
GridViewRow gdr = gd.Rows[e.RowIndex];
if (gdr != null)
{
txtAuthor = (TextBox)gd.Rows[e.RowIndex].FindControl("txtAuthor1");
txtBook = (TextBox)gd.Rows[e.RowIndex].FindControl("txtBook1");
dt = (DataTable)ViewState["dt"];
string txtAuthorName;
string txtBookName;
if (txtAuthor != null && txtBook!=null)
{
txtAuthorName = txtAuthor.Text;
txtBookName = txtBook.Text;
int i=0;
dt = (DataTable)Session["dt"];
for (; i < gd.Rows.Count; i++)
{
if (e.RowIndex == i)
{
dt.Rows[i][0] = txtAuthor.Text;
dt.Rows[i][1] = txtBook.Text;
ViewState["dt"] = dt;
gd.DataSource = dt;
gd.DataBind();
}
}
}
}
dt = (DataTable)ViewState["dt"];
gd.DataSource = dt;
gd.DataBind();
}
答案 0 :(得分:1)
错误可能是因为尝试访问不存在的一行数据表。要为datatable
行分配值,您必须检查datatable
中是否有该行检查grid
而不是datatable
的行。此处不需要循环您可以使用索引直接访问datatable
行,只需检查e.RowIndex
是否为datatable
的有效行索引。
if (e.RowIndex <= dt.Rows.Count)
{
dt.Rows[e.RowIndex][0] = txtAuthor.Text;
dt.Rows[e.RowIndex][1] = txtBook.Text;
ViewState["dt"] = dt;
gd.DataSource = dt;
gd.DataBind();
}