【问题标题】:How to add dynamically rows in datatable using textbox field ASP.NET如何使用文本框字段 ASP.NET 在数据表中动态添加行
【发布时间】:2017-05-08 11:57:48
【问题描述】:

我需要动态添加 3 个文本框字段

它可以工作,但问题是我无法保存预览记录,因为如果对象发生数据表重写。

 private void AgregarFila()
{
    dt.Columns.Add("Fecha", typeof(String));
    dt.Columns.Add("Documento", typeof(String));
    dt.Columns.Add("Folio", typeof(Int32));

    for (int i = 0; i <= 2; i++) // It is only for testing
    {
        dtRow = dt.NewRow();
        dtRow["Fecha"] = Session["HCfecha"];
        dtRow["Documento"] = Session["HCDocumento"];
        dtRow["Folio"] = Session["HCFolio"];
        dt.Rows.Add(dtRow);
    }
    gvHistoriaLaboral.DataSource = dt;
    gvHistoriaLaboral.DataBind();
}

View.aspx

<asp:DataGrid ID="gvHistoriaLaboral" GridLines="None" CssClass="table table-striped" runat="server"></asp:DataGrid>

帮助!

【问题讨论】:

  • 请澄清:你是说数据不会保存,当你绑定到网格时什么都没有显示?如果是这样,在 FOR LOOP 之后运行 dt.AccepChanges()。

标签: c# asp.net datatable webforms


【解决方案1】:

您应该将 DataTable 存储在 Session 中,以便以后可以访问,如下所示:

private void AgregarFila()
{
    if (Session["miTabla"] == null) //New table, create table and save it with the new record in Session variable
    {
        dt.Columns.Add("Fecha", typeof(String));
        dt.Columns.Add("Documento", typeof(String));
        dt.Columns.Add("Folio", typeof(Int32));
        dtRow = dt.NewRow();
        dtRow["Fecha"] = Session["HCfecha"];
        dtRow["Documento"] = Session["HCDocumento"];
        dtRow["Folio"] = Session["HCFolio"];
        dt.Rows.Add(dtRow);
        Session["miTabla"] = dt;
    }
   else
    {
        dt = (DataTable) Session["miTabla"]; //Read Session variable
        for (int i = 0; i <= 2; i++)
        {
           dtRow = dt.NewRow();
           dtRow["Fecha"] = Session["HCfecha"];
           dtRow["Documento"] = Session["HCDocumento"];
           dtRow["Folio"] = Session["HCFolio"];
           dt.Rows.Add(dtRow);
        }
        Session["miTabla"] = dt;   //Write Session variable after record added     
   }
    gvHistoriaLaboral.DataSource = dt;
    gvHistoriaLaboral.DataBind();
}

Session 变量值保留在当前用户会话中,因此每当插入新记录时,您只需读取该变量,将其解析为 DataTable,添加新记录,然后将 DataTable 存储回 Session 中。

欲了解更多信息或其他方式:ASP .NET State Management

问候!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多