System.Data Namespace DataTable Class
Initializes a new DataRow with the same schema as the table.
[ VB ]
Public Function NewRow ( ) As DataRow
[ C# ]
public DataRow NewRow ( );
[ C++ ]
public: DataRow* NewRow ( );
[ JScript ]
public function NewRow ( ) : DataRow;
A DataRow with the same schema as the DataTable.
You must use the NewRow method to create new DataRow objects with the same schema as the DataTable. After creating a DataRow, you can add it to the DataRowCollection, through the DataTable object's Rows property.
The following example initializes a DataTable, adds two DataColumn objects that determine the table's schema, and initializes several new DataRow objects using the NewRow method. Those DataRow objects are then added to the DataRowCollection using the Add method.
Private void MakeDataTableAndDisplay ( ) {
// create new DataTable and DataSource objects.
DataTable myDataTable = new DataTable ( );
// declare DataColumn and DataRow variables.
DataColumn myColumn;
DataRow myRow;
DataView myDataView;
// create new DataColumn, set DataType, ColumnName and add to DataTable.
myColumn = new DataColumn ( );
myColumn.DataType = System.Type.GetType ( "System.Int32" );
myColumn.ColumnName = "id";
myDataTable.Columns.Add ( myColumn );
// create second column.
myColumn = new DataColumn ( );
myColumn.DataType = Type.GetType ( "System.String" );
myColumn.ColumnName = "item";
myDataTable.Columns.Add ( myColumn );
// create new DataRow objects and add to DataTable.
for ( int i = 0; i < 10; i++ ) {
myRow = myDataTable.NewRow ( );
myRow [ "id" ] = i;
myRow [ "item" ] = "item " + i.ToString ( );;
myDataTable.Rows.Add ( myRow );
}
// create a DataView using the DataTable.
myDataView = new DataView ( myDataTable );
// set a DataGrid control's DataSource to the DataView.
myDataGrid.DataSource = myDataView;
}
Private Sub MakeDataTableAndDisplay ( )
' create new DataTable and DataSource objects.
Dim myDataTable As DataTable = New DataTable ( )
' declare DataColumn and DataRow variables.
Dim myColumn As DataColumn
Dim myRow As DataRow
Dim myDataView As DataView
' create new DataColumn, set DataType, ColumnName and add to DataTable.
myColumn = New DataColumn ( )
myColumn.DataType = System.Type.GetType ( "System.Int32" )
myColumn.ColumnName = "id"
myDataTable.Columns.Add ( myColumn )
' create second column.
myColumn = New DataColumn ( )
myColumn.DataType = Type.GetType ( "System.String" )
myColumn.ColumnName = "item"
myDataTable.Columns.Add ( myColumn )
' create new DataRow objects and add to DataTable.
Dim i As Integer
For i = 0 to 9
myRow = myDataTable.NewRow ( )
myRow ( "id" ) = i
myRow ( "item" ) = "item " & i
myDataTable.Rows.Add ( myRow )
Next
' create a DataView using the DataTable.
myDataView = New DataView ( myDataTable )
' set a DataGrid control's DataSource to the DataView.
myDataGrid.DataSource = myDataView
End Sub |
|
C# |
VB |
DataTable Members AcceptChanges Add DataColumnCollection DataColumn DataRowCollection