无法在DataTable中添加行

时间:2014-02-06 14:11:09

标签: c# asp.net gridview

我正在尝试在DataTable中添加一个新行,其中的值来自GridView行。以下是我正在使用的代码:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Save")
    {
        DataTable dt = new DataTable();
        dt = (DataTable)ViewState["CurrentStuDt"];
        DataRow dr = null;
        dr = dt.NewRow();
        dr["ID"] = Convert.ToInt32(gv.FooterRow.FindControl("txtInId"));
        dr["Name"] = gv.FooterRow.FindControl("txtIName");
        dr["Class"] = gv.FooterRow.FindControl("txtIClass");
        dr["Section"] = gv.FooterRow.FindControl("txtISec");
        dt.Rows.Add(dr);

        ViewState["CurrentStuDt"] = dt;

        gv.DataSource = dt;
        gv.DataBind();
    }
}

但是我收到以下错误:

Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.IConvertible'.

在线

dr["ID"] = Convert.ToInt32(gv.FooterRow.FindControl("txtInId"));

2 个答案:

答案 0 :(得分:1)

gv.FooterRow.FindControl("txtInId")

会给你控件而不是它的值。尝试像

这样的东西
TextBox myText = (TextBox)gv.FooterRow.FindControl("txtInId");
dr["ID"] = Convert.ToInt32(myText.Text);

答案 1 :(得分:0)

int rowIndex = Convert.ToInt16(e.CommandArgument);

dr["ID"] = Convert.ToInt32(((TextBox)gv.Rows[rowIndex].FindControl("txtInId")).Text.ToString());