Insert a new row into DataTable

后端 未结 4 427
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 17:12

I have a datatable filled with staff data like..

Staff 1 - Day 1 - Total
Staff 1 - Day 2 - Total
Staff 1 - Day 3 - Total
Staff 2 - Day 1 - Total
Staff 2 - Da         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-13 17:51

    @William You can use NewRow method of the datatable to get a blank datarow and with the schema as that of the datatable. You can populate this datarow and then add the row to the datatable using .Rows.Add(DataRow) OR .Rows.InsertAt(DataRow, Position). The following is a stub code which you can modify as per your convenience.

    //Creating dummy datatable for testing
    DataTable dt = new DataTable();
    DataColumn dc = new DataColumn("col1", typeof(String));
    dt.Columns.Add(dc);
    
    dc = new DataColumn("col2", typeof(String));
    dt.Columns.Add(dc);
    
    dc = new DataColumn("col3", typeof(String));
    dt.Columns.Add(dc);
    
    dc = new DataColumn("col4", typeof(String));
    dt.Columns.Add(dc);
    
    DataRow dr = dt.NewRow();
    
    dr[0] = "coldata1";
    dr[1] = "coldata2";
    dr[2] = "coldata3";
    dr[3] = "coldata4";
    
    dt.Rows.Add(dr);//this will add the row at the end of the datatable
    //OR
    int yourPosition = 0;
    dt.Rows.InsertAt(dr, yourPosition);
    

提交回复
热议问题