【问题标题】:Unable to add a row in DataTable无法在 DataTable 中添加行
【发布时间】:2014-02-06 14:11:09
【问题描述】:

我正在尝试在 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"));

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:
    gv.FooterRow.FindControl("txtInId")
    

    会给你控制而不是其中的价值。尝试类似

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

    【讨论】:

    • 我收到一个错误,'TextBox' 是 'System.Web.UI.WebControls.TextBox' 和 'System.Windows.Forms.TextBox' 之间的模糊引用,因为我使用的是 'System .Windows.Forms 的命名空间
    • 尝试使用 System.Windows.Forms.TextBox myText = (System.Windows.Forms.TextBox)gv.FooterRow.FindControl("txtInId"); 之类的控件添加命名空间;
    【解决方案2】:
    int rowIndex = Convert.ToInt16(e.CommandArgument);
    
    dr["ID"] = Convert.ToInt32(((TextBox)gv.Rows[rowIndex].FindControl("txtInId")).Text.ToString());
    

    【讨论】:

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