How to create a DataTable in C# and how to add rows?

后端 未结 13 2302
星月不相逢
星月不相逢 2020-11-28 01:35

How do create a DataTable in C#?

I did like this:

 DataTable dt = new DataTable();
 dt.clear();
 dt.Columns.Add(\"Name\");
 dt.Columns.Add(\"Marks\")         


        
相关标签:
13条回答
  • 2020-11-28 02:13

    Question 1: How do create a DataTable in C#?

    Answer 1:

    DataTable dt = new DataTable(); // DataTable created
    
    // Add columns in your DataTable
    dt.Columns.Add("Name");
    dt.Columns.Add("Marks");
    

    Note: There is no need to Clear() the DataTable after creating it.

    Question 2: How to add row(s)?

    Answer 2: Add one row:

    dt.Rows.Add("Ravi","500");
    

    Add multiple rows: use ForEach loop

    DataTable dt2 = (DataTable)Session["CartData"]; // This DataTable contains multiple records
    foreach (DataRow dr in dt2.Rows)
    {
        dt.Rows.Add(dr["Name"], dr["Marks"]);
    }
    
    0 讨论(0)
提交回复
热议问题