閱讀英文

共用方式為


DataTable.NewRow 方法

定義

使用與資料表相同的結構描述來建立新的 DataRow

C#
public System.Data.DataRow NewRow ();

傳回

DataRow,具有與 DataTable 相同的結構描述。

範例

下列範例會建立 、加入兩DataColumnDataTable對象來判斷數據表的架構,並使用 方法建立數個新DataRow物件NewRow。 然後,這些DataRow物件會使用 Add 方法新增至 DataRowCollection

C#
private void MakeDataTableAndDisplay()
{
    // Create new DataTable and DataSource objects.
    DataTable table = new DataTable();

    // Declare DataColumn and DataRow variables.
    DataColumn column;
    DataRow row;
    DataView view;

    // Create new DataColumn, set DataType, ColumnName and add to DataTable.
    column = new DataColumn();
    column.DataType = System.Type.GetType("System.Int32");
    column.ColumnName = "id";
    table.Columns.Add(column);

    // Create second column.
    column = new DataColumn();
    column.DataType = Type.GetType("System.String");
    column.ColumnName = "item";
    table.Columns.Add(column);

    // Create new DataRow objects and add to DataTable.
    for(int i = 0; i < 10; i++)
    {
        row = table.NewRow();
        row["id"] = i;
        row["item"] = "item " + i.ToString();
        table.Rows.Add(row);
    }

    // Create a DataView using the DataTable.
    view = new DataView(table);

    // Set a DataGrid control's DataSource to the DataView.
    dataGrid1.DataSource = view;
}

備註

您必須使用 NewRow 方法來建立架構與 DataTable相同的新DataRow物件。 建立 DataRow之後,您可以透過 DataTable 物件的 Rows 屬性將它新增至 DataRowCollection。 當您用來 NewRow 建立新資料列時,必須先在資料表中加入或刪除資料列,才能呼叫 Clear

適用於

產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

另請參閱