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

我是这样做的:

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

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

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


当前回答

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

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

其他回答

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

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

添加一行。

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

看结构:

Table.Columns

问题1:如何在c#中创建数据表?

回答1:

DataTable dt = new DataTable(); // DataTable created

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

注意:创建数据表后不需要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"]);
}

目前最简单的方法是创建一个DtaTable

DataTable table = new DataTable
{
    Columns = {
        "Name", // typeof(string) is implied
        {"Marks", typeof(int)}
    },
    TableName = "MarksTable" //optional
};
table.Rows.Add("ravi", 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);