23.4 Methods Reference

AcceptChanges

DataTable.AcceptChanges();

Commits all changes made to the DataTable since the last time it was loaded or the last time AcceptChanges( ) was called.

Parameters

None.

Example

The following example demonstrates how to call the AcceptChanges( ) method of the DataTable and the effect of calling AcceptChanges( ) on the row state:

// create a table with a single column
DataTable dt = new DataTable();
dt.Columns.Add("MyColumn", typeof(System.Int32));

DataRow row;
row = dt.NewRow();
row["MyColumn"] = 1;
dt.Rows.Add(row);       // RowState = Added

dt.AcceptChanges();     // RowState = Unchanged

row["MyColumn"] = 2;    // RowState = Modified
dt.AcceptChanges();     // RowState = Unchanged

row.Delete();           // RowState = Deleted
dt.AcceptChanges();     // Row is removed from the DataTable

Notes

Calling AcceptChanges( ) sets the RowState property of Added and Modified rows to Unchanged; the original values in the DataRow are set to the current values. Deleted rows are removed from the DataTable.

Calling the AcceptChanges( ) method on the DataTable causes AcceptChanges to be called on each DataRow belonging to the DataTable. Calling the AcceptChanges( ) method of a DataSet that the table belongs to implicitly calls the AcceptChanges( ) method of the table.

EndEdit( ) is implicitly called on any DataRow objects that are in edit mode as a result of calling the BeginEdit( ) method of the DataRow.

Calling AcceptChanges( ) clears all RowError information and sets the HasErrors property of the row to false.

BeginLoadData

DataTable.BeginLoadData();

Turns off constraints, notifications, and index maintenance for the DataTable.

Parameters

None.

Example

The following example shows how to use the BeginLoadData( ) and EndLoadData( ) methods to load data into a DataTable:

dt.BeginLoadData();

// load two rows to the DataTable dt
dt.LoadDataRow(new Object[]{1,"Row 1"}, false);
dt.LoadDataRow(new Object[]{2,"Row 2"}, false);

dt.EndLoadData();

Notes

Calling BeginLoadData( ) and EndLoadData( ) methods might result in performance improvements when adding multiple rows to a table with the LoadDataRow( ) method, although this isn't required.

The EndLoadData( ) method turns on constraints, notifications, and index maintenance for the DataTable after they have been turned off by BeginLoadData( ).

Clear

DataTable.Clear();

Removes all rows from the DataTable.

Parameters

None.

Example

The following example demonstrates how to use the Clear( ) method of the DataTable:

DataTable dt = new DataTable();

// ... define the schema for the DataTable

// ... add some rows to the table

dt.Clear();    // all rows are removed from the table.

Note

An exception is generated if the Clear( ) operation deletes a parent row for a child row in an enforced relationship.

Clone

DataTable cloneTable = DataTable.Clone();

Creates a new DataTable with the same schema as the current DataTable but containing none of the data.

Parameter

cloneTable

Returns a DataTable with the same schema but none of the data of the original DataTable.

Example

The following example shows how to create a new empty DataTable with the same schema as an existing DataTable:

DataSet dt1 = new DataTable();

// ... define the schema for the DataTable

// ... add some rows to the DataTable

// Create DataTable dt2 with the same schema, but without any of the 
// data in DataTable dt1.
DataTable dt2 = dt1.Clone();
Compute

Object obj = DataTable.Compute(String expression, String filter);

Returns the result of an aggregate expression for a subset of rows in the table meeting the filter criteria.

Parameters

obj

Returns an object containing the results computed.

expression

The expression to calculate.

filter

A filter that identifies a subset of rows for which the expression is computed.

Example

The following example demonstrates how to use the Compute( ) method to calculate the sum of a column for a subset of the rows filtered from the table:

DataTable dt = new DataTable();
dt.Columns.Add("OrderId", typeof(System.Int32));
dt.Columns.Add("OrderAmount", typeof(System.Decimal));

// ... add some rows

// computes the sum of order amounts for all orders with Id less than 10
Decimal totalOrderAmount= 
  (Decimal) dt.Compute("SUM(OrderAmount)", "OrderId<10");

Note

The expression must be set to an aggregate function. To compute a value based on an expression, create a DataColumn based on the expression and use that column in the expression.

Copy

DataTable copyTable = DataTable.Copy();

Creates a new DataTable with the same schema and data as the current DataTable.

Parameter

copyTable

Returns a DataTable with the same schema and data as the original DataTable.

Example

The following example shows how to create a new empty DataTable with the same schema and data as an existing DataTable:

DataSet dt1 = new DataTable();

// ... define the schema for the DataTable

// ... add some rows to the DataTable

// Create DataTable dt2 with the same schema and data as DataTable dt1.
DataTable dt2 = dt1.Copy();
EndLoadData

DataTable.EndLoadData();

Turns on constraints, notifications, and index maintenance that were turned off by BeginLoadData( ).

Parameters

None.

Example

See the Example for the BeginLoadData( ) method in this chapter.

Notes

Calling BeginLoadData( ) and EndLoadData( ) methods might result in performance improvements when adding multiple rows to a table with the LoadDataRow( ) method.

The BeginLoadData( ) method turns off the constraints, notifications, and index maintenance for the DataTable.

If there are constraint violations when the EndLoadData( ) method is called, a ConstraintException event is raised.

GetChanges

DataTable changeTable = DataTable.GetChanges();
DataTable changeTable = DataTable.GetChanges(DataRowState drs);

Returns a DataTable with the same schema as the original DataTable, but containing only the rows that have been modified since the last time the DataSet was loaded or since AcceptChanges( ) was last called. This overloaded method allows the changes to be filtered by the RowState of the DataRow objects.

Parameters

changeTable

Returns the DataTable with all changes made to the original since it was last loaded or since AcceptChanges( ) was last called.

drs

A value from the DataRowState enumeration described in Table 23-13 specifying the state of the DataRow objects to return.

Example

The following example shows how to create a DataTable containing only the changed rows from the original DataTable using the GetChanges( ) method:

DataSet dsChanges = dsOriginal.GetChanges();

Notes

The GetChanges( ) method can isolate the rows that have been changed so that the entire DataTable doesn't have to be passed to a method that reconciles DataTable changes with the data source.

A null reference is returned if there are no rows matching the specified criteria.

GetErrors

DataRow[] errorRows = DataTable.GetErrors();

Gets an array of DataRow objects that contain errors.

Parameter

errorRows

Returns an array of DataRow objects that are the rows in the DataTable with errors.

Example

The following example demonstrates using the GetErrors( ) method to return the array of rows that have errors:

DataRow[] errorRows;
if(dt.HasErrors)
{

    errorRows = dt.GetErrors();
    for(Int32 i = 0; i<errorRows.Length; i++)
    {
        // ... resolve the error for the row

        // clear the error for resubmitting
        errorRows[i].ClearErrors();
    }
}

Notes

The GetErrors( ) method returns a DataRow array of the rows that contain errors, both constraint violations and failed update attempts.

To improve performance, call HasErrors( ) on the DataTable prior to calling GetErrors( ) to determine whether there are any errors.

ImportRow

DataTable.ImportRow(DataRow row);

Copies a DataRow to the DataTable.

Parameter

row

The DataRow to import into the current DataTable.

Example

The following example demonstrates how to use the ImportRow( ) method to add a row to a table:

DataRow newRow = dt.NewRow();
newRow["Column1"] = 1;
newRow["Column2"] = "Row 1";

dt.Rows.ImportRow(newRow);

Notes

The ImportRow( ) can add rows from other tables or rows that were not created using the NewRow( ) method to the table.

The existing DataRowState and other values in the row are preserved.

LoadDataRow

DataRow row = DataTable.LoadDataRow(Object[] values,
    Boolean acceptChanges);

Finds a DataRow in the DataTable and updates the values with the values in the supplied array. If the row isn't found, a new row is added to the DataTable.

Parameters

row

Returns the DataRow that has been loaded into the DataTable.

values

An array of objects containing the column values for the row to load into the DataSet.

acceptChanges

A value indicating whether AcceptChanges( ) should be called on the row loaded into the DataTable.

Example

This example demonstrates adding a new row to the Northwind Shippers table:

ds.Tables["Shippers"].BeginLoadData();

ds.Tables["Shippers"].LoadDataRow(new object[] {null,
    "NewShipperCompanyName", "NewShipperPhone"}, true);

// ... load some more rows

ds.Tables["Shippers"].EndLoadData();

Notice that a null value is passed for the array element corresponding to the ShipperID column that is an AutoIncrement column.

Notes

The LoadDataRow( ) method takes an array of values and attempts to find a row with a matching primary key. If the primary key is found, the values replace the existing data for the row; otherwise a new row is added.

If a column has a default value or is an AutoIncrement column, pass null in the array for that column.

While not required, using LoadDataRow( ) together with the BeginLoadData( ) and EndLoadData( ) methods might improve performance.

An ArgumentException is raised if the array is larger than the number of columns in the table. If a value in the array doesn't match the respective column type, an InvalidCastException is raised. A ConstraintException is raised if adding the row violates a constraint. Finally, NoNullAllowedException is raised if an attempt is made to set a column to null when AllowDBNull is false for that column.

NewRow

DataRow newRow = DataTable.NewRow();

Returns a new DataRow with the same schema as the DataTable.

Parameter

newRow

Returns a new, empty DataRow with the same schema as the DataTable.

Example

The following example demonstrates how to create a new row and add the row to a DataTable using the Add( ) method of the DataRowCollection:

// create the target table
DataTable dt = new DataTable("MyTable");
dt.Columns.Add("Column1", typeof(System.Int32));
dt.Columns.Add("Column2", typeof(System.String));

// create and add a new row to the table
DataRow newRow=dt.NewRow();
newRow["Column1"] = 1;
newRow["Column2"] = "Row 1";
dt.Rows.Add(newRow);
RejectChanges

DataTable.RejectChanges();

Rejects all changes made to the DataTable since the last time it was loaded or since the last time AcceptChanges( ) was called.

Parameters

None.

Example

The following example demonstrates how to call the RejectChanges( ) method of the DataTable:

// create a table with a single column
DataTable dt = new DataTable();
dt.Columns.Add("MyColumn", typeof(System.Int32));

DataRow row;
row = dt.NewRow();
row["MyColumn"] = 1;
dt.Rows.Add(row);       // RowState = Added
dt.AcceptChanges();     // RowState = Unchanged

row["MyColumn"] = 2;    // RowState = Modified
dt.RejectChanges();     // RowState = Unchanged, row["MyColumn"] = 1

row.Delete();           // RowState = Deleted
dt.RejectChanges();     // RowState = Unchanged
                        // The row isn't removed from the DataTable.

Notes

Calling RejectChanges( ) sets the RowState property of Deleted and Modified rows to Unchanged; the current values in the DataRow are set to the original values. Added rows are removed.

Calling the RejectChanges( ) method on the DataTable causes RejectChanges( ) to be called on each DataRow belonging to the DataTable. Calling the RejectChanges( ) method of the DataSet that the table belongs to implicitly calls the RejectChanges( ) method of the table.

Any DataRows in edit mode as a result of calling BeginEdit( ) cancel their edits when RejectChanges( ) is called.

Calling RejectChanges( ) clears all RowError information and sets the HasErrors property to false.

Reset

DataTable.Reset();

Discards the contents of the DataTable, resetting it to an uninitialized state.

Parameters

None.

Example

The following example shows how reset a DataSet to its original state:

ds.Reset();

Note

Calling Reset( ) on an existing DataTable is more efficient than instantiating a new DataTable.

Select

DataRow[] selectRow = DataTable.Select();
DataRow[] selectRow = DataTable.Select(String filter);
DataRow[] selectRow = DataTable.Select(String filter, String sortOrder);
DataRow[] selectRow = DataTable.Select(String filter, String sortOrder,
    DataViewRowState dvrs);

Returns an array of DataRow objects that matches the optional filter and DataViewRowState specified. The sort criteria can be specified to control the order of the objects in the returned DataRow array.

Parameters

selectRow

Returns an array of DataRow objects matching the optional select criteria and row state, ordered as specified by the optional sort order parameter.

filter

The filter criteria used to select the rows.

sortOrder

The sort order and direction for the returned rows within the array.

dvrs

The row state of the rows to be returned. This is a value from the DataViewRowState enumeration described in Table 28-1.

Example

The following example demonstrates selecting rows from a data table specifying both a filter and sort order:

// all rows with order amount > 100, sorted on the order date descending
DataRow[] dra = dt.Select("OrderAmount>100.00", "OrderDate DESC");

Note

The arguments specifying both the filter and sort order follow standard rules for creating expression strings.



    Part I: ADO.NET Tutorial
    Part II: ADO.NET Core Classes
    Part III: API Quick Reference