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

后端 未结 13 2392
星月不相逢
星月不相逢 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:07

    // Create a DataTable and add two Columns to it
    DataTable dt=new DataTable();
    dt.Columns.Add("Name",typeof(string));
    dt.Columns.Add("Age",typeof(int));
    
    // Create a DataRow, add Name and Age data, and add to the DataTable
    DataRow dr=dt.NewRow();
    dr["Name"]="Mohammad"; // or dr[0]="Mohammad";
    dr["Age"]=24; // or dr[1]=24;
    dt.Rows.Add(dr);
    
    // Create another DataRow, add Name and Age data, and add to the DataTable
    dr=dt.NewRow();
    dr["Name"]="Shahnawaz"; // or dr[0]="Shahnawaz";
    dr["Age"]=24; // or dr[1]=24;
    dt.Rows.Add(dr);
    
    // DataBind to your UI control, if necessary (a GridView, in this example)
    GridView1.DataSource=dt;
    GridView1.DataBind();
    

提交回复
热议问题