次の方法で共有


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

戻り値

DataTableと同じスキーマを持つDataRow

次の例では、DataTableを作成し、テーブルのスキーマを決定する 2 つのDataColumn オブジェクトを追加し、NewRow メソッドを使用して新しいDataRow オブジェクトをいくつか作成します。 これらの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

注釈

DataTableと同じスキーマを持つ新しいDataRow オブジェクトを作成するには、NewRow メソッドを使用する必要があります。 DataRowを作成した後、DataTable オブジェクトのRows プロパティを使用して、DataRowCollectionに追加できます。 NewRowを使用して新しい行を作成する場合は、Clearを呼び出す前に、データ テーブルに行を追加するか、データ テーブルから削除する必要があります。

適用対象

こちらもご覧ください