如何在c#中创建一个数据表?

我是这样做的:

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

我如何看到数据表的结构?

现在我想为Name添加ravi,为Marks添加500。我该怎么做呢?


当前回答

您可以在单行中添加Row

    DataTable table = new DataTable();
    table.Columns.Add("Dosage", typeof(int));
    table.Columns.Add("Drug", typeof(string));
    table.Columns.Add("Patient", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    // Here we add five DataRows.
    table.Rows.Add(25, "Indocin", "David", DateTime.Now);
    table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
    table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
    table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
    table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

其他回答

// 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);

添加一行。

DataRow row = dt.NewRow();
row["Name"] = "Ravi";
row["Marks"] = 500;
dt.Rows.Add(row);

看结构:

Table.Columns

为此,您必须向数据表中添加数据箭头。

// 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 );

除了其他答案。

如果你控制数据表的结构,有一个添加行的快捷方式:

//假设您有一个数据表,定义为示例中的dt dt.Rows。添加(“名称”、“商标”);

add()方法有一个重载,它接受一个对象的参数数组。此方法允许您根据需要传递任意数量的值,但它们必须与表中定义的列的顺序相同。

因此,虽然这是一种方便的添加行数据的方法,但使用它可能有风险。如果表结构改变,代码将失败。