如何在c#中创建一个数据表?
我是这样做的:
DataTable dt = new DataTable();
dt.clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
我如何看到数据表的结构?
现在我想为Name添加ravi,为Marks添加500。我该怎么做呢?
如何在c#中创建一个数据表?
我是这样做的:
DataTable dt = new DataTable();
dt.clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
我如何看到数据表的结构?
现在我想为Name添加ravi,为Marks添加500。我该怎么做呢?
当前回答
创建datatabe的2列:名称和标记 IList columns = new List() {"Name", "Marks"}; Datatabel dt = new Datatable(); Foreach(列中的字符串列) dtSalesOrder.Columns。添加(列,typeof (string)); 向数据表中添加数据 dt.Rows.Add(“拉”,“500”);
其他回答
除了其他答案。
如果你控制数据表的结构,有一个添加行的快捷方式:
//假设您有一个数据表,定义为示例中的dt dt.Rows。添加(“名称”、“商标”);
add()方法有一个重载,它接受一个对象的参数数组。此方法允许您根据需要传递任意数量的值,但它们必须与表中定义的列的顺序相同。
因此,虽然这是一种方便的添加行数据的方法,但使用它可能有风险。如果表结构改变,代码将失败。
// 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();
目前最简单的方法是创建一个DtaTable
DataTable table = new DataTable
{
Columns = {
"Name", // typeof(string) is implied
{"Marks", typeof(int)}
},
TableName = "MarksTable" //optional
};
table.Rows.Add("ravi", 500);
你也可以传入一个对象数组,像这样:
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
object[] o = { "Ravi", 500 };
dt.Rows.Add(o);
甚至:
dt.Rows.Add(new object[] { "Ravi", 500 });
创建datatabe的2列:名称和标记 IList columns = new List() {"Name", "Marks"}; Datatabel dt = new Datatable(); Foreach(列中的字符串列) dtSalesOrder.Columns。添加(列,typeof (string)); 向数据表中添加数据 dt.Rows.Add(“拉”,“500”);