// Creates a new DataRow with the same schema as the table.
DataRow dr = dt.NewRow();
// Fill the values
dr["Name"] = "Name";
dr["Marks"] = "Marks";
// Add the row to the rows collection
dt.Rows.Add ( dr );
// 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();
DataTable dt=new DataTable();
Datacolumn Name = new DataColumn("Name");
Name.DataType= typeoff(string);
Name.AllowDBNull=false; //set as null or not the default is true i.e null
Name.MaxLength=20; //sets the length the default is -1 which is max(no limit)
dt.Columns.Add(Name);
Datacolumn Age = new DataColumn("Age", typeoff(int));`
dt.Columns.Add(Age);
DataRow dr=dt.NewRow();
dr["Name"]="Mohammad Adem"; // or dr[0]="Mohammad Adem";
dr["Age"]=33; // or dr[1]=33;
dt.add.rows(dr);
dr=dt.NewRow();
dr["Name"]="Zahara"; // or dr[0]="Zahara";
dr["Age"]=22; // or dr[1]=22;
dt.rows.add(dr);
Gv.DataSource=dt;
Gv.DataBind();
DataTable dt = new DataTable(); // DataTable created
// Add columns in your DataTable
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
在创建DataTable后,不需要Clear()它。
问题2:如何添加行?
答案2:增加一行:
dt.Rows.Add("Ravi","500");
添加多行:使用ForEach循环
DataTable dt2 = (DataTable)Session["CartData"]; // This DataTable contains multiple records
foreach (DataRow dr in dt2.Rows)
{
dt.Rows.Add(dr["Name"], dr["Marks"]);
}