DataTable.NewRow 方法

定義

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

public:
 System::Data::DataRow ^ NewRow();
public System.Data.DataRow NewRow ();
member this.NewRow : unit -> System.Data.DataRow
Public Function NewRow () As DataRow

傳回

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

範例

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

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;
}
Private Sub MakeDataTableAndDisplay()
    ' Create new DataTable and DataSource objects.
    Dim table As New DataTable()

    ' Declare DataColumn and DataRow variables.
    Dim column As DataColumn 
    Dim row As DataRow 
    Dim view As DataView 

    ' 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.    
    Dim i As Integer
    For i = 0 to 9 
       row = table.NewRow()
       row("id") = i
       row("item") = "item " & i
       table.Rows.Add(row)
    Next
    ' Create a DataView using the DataTable.
    view = New DataView(table)

    ' Set a DataGrid control's DataSource to the DataView.
    DataGrid1.DataSource = view
End Sub

備註

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

適用於

另請參閱