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

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

    In addition to the other answers.

    If you control the structure of the DataTable there is a shortcut for adding rows:

    // Assume you have a data table defined as in your example named dt dt.Rows.Add("Name", "Marks");

    The DataRowCollection.Add() method has an overload that takes a param array of objects. This method lets you pass as many values as needed, but they must be in the same order as the columns are defined in the table.

    So while this is a convenient way to add row data, it can be risky to use. If the table structure changes your code will fail.

提交回复
热议问题