在RowUpdating中设置数据表中的值

时间:2013-04-13 11:51:52

标签: c# asp.net .net

 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();
    }

1 个答案:

答案 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();
}