GridView 动态添加行并且刷新后保留记录

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
               createTable();
          }
    } 

private void createTable()      //创建一个表
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("filepath", typeof(string));
        HttpContext.Current.Session["document"] = dt;
        pub.BindGrid(gv_uploadfile, dt);       //绑定gridview ,pub为自定义类
    }
    private void addColumn()
    {
        DataRow dr = (HttpContext.Current.Session["document"] as DataTable).NewRow();
        dr["filepath"] =  DBNull.Value;                                                   //添加表的字段,这里只添加一个字段为例

      
        (HttpContext.Current.Session["document"] as DataTable).Rows.Add(dr);
    }
    private DataTable alterData(GridView gv)       //遍历gridview,并记录数据
    {
        DataTable dt = (DataTable)HttpContext.Current.Session["document"];
            dt.Clear();
            for (int i = 0; i < gv.Rows.Count; i++)
            {
                DataRow dr = dt.NewRow();
                dr["filepath"] = gv.Rows[i].Cells[1].Text;
                dt.Rows.Add(dr);
            }
            return dt;
        }

 protected void btn_addDocument_Click(object sender, EventArgs e)  
    {  
       
        if ((HttpContext.Current.Session["document"] as DataTable) != null)
        {
            HttpContext.Current.Session["document"] = alterData(gv_uploadfile);
        }
        addColumn();                                                                     //添加一行
        pub.BindGrid(gv_uploadfile, (DataTable)HttpContext.Current.Session["document"]);
          }

原文地址:https://www.cnblogs.com/sherry/p/1301514.html