Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

DataTable.Load Method (IDataReader, LoadOption, FillErrorEventHandler)

Fills a DataTable with values from a data source using the supplied IDataReader using an error-handling delegate.

Namespace:  System.Data
Assembly:  System.Data (in System.Data.dll)
public virtual void Load(
	IDataReader reader,
	LoadOption loadOption,
	FillErrorEventHandler errorHandler
)

Parameters

reader
Type: System.Data.IDataReader

A IDataReader that provides a result set.

loadOption
Type: System.Data.LoadOption

A value from the LoadOption enumeration that indicates how rows already in the DataTable are combined with incoming rows that share the same primary key.

errorHandler
Type: System.Data.FillErrorEventHandler

A FillErrorEventHandler delegate to call when an error occurs while loading data.

The Load method consumes the first result set from the loaded IDataReader, and after successful completion, sets the reader's position to the next result set, if any. When converting data, the Load method uses the same conversion rules as the DbDataAdapter.Fill method.

The Load method must take into account three specific issues when loading the data from an IDataReader instance: schema, data, and event operations. When working with the schema, the Load method may encounter conditions as described in the following table. The schema operations take place for all imported result sets, even those containing no data.

Condition

Behavior

The DataTable has no schema.

The Load method infers the schema based on the result set from the imported IDataReader.

The DataTable has a schema, but it is incompatible with the loaded schema.

The Load method throws an exception corresponding to the particular error that occurs when attempting to load data into the incompatible schema.

The schemas are compatible, but the loaded result set schema contains columns that don't exist in the DataTable.

The Load method adds the extra column(s) to DataTable’s schema. The method throws an exception if corresponding columns in the DataTable and the loaded result set are not value compatible. The method also retrieves constraint information from the result set for all added columns. Except for the case of Primary Key constraint, this constraint information is used only if the current DataTable does not contain any columns at the start of the load operation.

The schemas are compatible, but the loaded result set schema contains fewer columns than does the DataTable.

If a missing column has a default value defined or the column's data type is nullable, the Load method allows the rows to be added, substituting the default or null value for the missing column. If no default value or null can be used, then the Load method throws an exception. If no specific default value has been supplied, the Load method uses the null value as the implied default value.

Before considering the behavior of the Load method in terms of data operations, consider that each row within a DataTable maintains both the current value and the original value for each column. These values may be equivalent, or may be different if the data in the row has been changed since filling the DataTable. See Row States and Row Versions for more information.

In this method call, the specified LoadOption parameter influences the processing of the incoming data. How should the Load method handle loading rows that have the same primary key as existing rows? Should it modify current values, original values, or both? These issues, and more, are controlled by the loadOption parameter.

If the existing row and the incoming row contain corresponding primary key values, the row is processed using its current row state value, otherwise it's treated as a new row.

In terms of event operations, the RowChanging event occurs before each row is changed, and the RowChanged event occurs after each row has been changed. In each case, the Action property of the DataRowChangeEventArgs instance passed to the event handler contains information about the particular action associated with the event. This action value varies, depending on the state of the row before the load operation. In each case, both events occur, and the action is the same for each. The action may be applied to either the current or original version of each row, or both, depending on the current row state.

The following table displays behavior for the Load method when called with each of the LoadOption values, and also shows how the values interact with the row state for the row being loaded. The final row (labeled "(Not present)") describes the behavior for incoming rows that don't match any existing row. Each cell in this table describes the current and original value for a field within a row, along with the DataRowState for the value after the Load method has completed.

Existing DataRowState

Upsert

OverwriteChanges

PreserveChanges (Default behavior)

Added

Current = <Incoming>

Original = -<Not available>

State = <Added>

RowAction = Change

Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal

Current = <Existing>

Original = <Incoming>

State = <Modified>

RowAction = ChangeOriginal

Modified

Current = <Incoming>

Original = <Existing>

State = <Modified>

RowAction = Change

Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal

Current = <Existing>

Original = <Incoming>

State = <Modified>

RowAction =ChangeOriginal

Deleted

(Load does not affect deleted rows)

Current = ---

Original = <Existing>

State = <Deleted>

(New row is added with the following characteristics)

Current = <Incoming>

Original = <Not available>

State = <Added>

RowAction = Add

Undo delete and

Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal

Current = <Not available>

Original = <Incoming>

State = <Deleted>

RowAction = ChangeOriginal

Unchanged

Current = <Incoming>

Original = <Existing>

If new value is the same as the existing value then

State = <Unchanged>

RowAction = Nothing

Else

State = <Modified>

RowAction = Change

Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal

Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal

(Not present)

Current = <Incoming>

Original = <Not available>

State = <Added>

RowAction = Add

Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal

Current = <Incoming>

Original = <Incoming>

State = <Unchanged>

RowAction = ChangeCurrentAndOriginal

Values in a DataColumn can be constrained through use of properties such as ReadOnly and AutoIncrement. The Load method handles such columns in a manner that is consistent with the behavior defined by the column's properties. The read only constraint on a DataColumn is applicable only for changes that occur in memory. The Load method's overwrites the read-only column values, if needed.

If you specify the OverwriteChanges or PreserveChanges options when calling the Load method, then the assumption is made that the incoming data is coming from the DataTable's primary data source, and the DataTable tracks changes and can propagate the changes back to the data source. If you select the Upsert option, it is assumed that the data is coming from one of a secondary data source, such as data provided by a middle-tier component, perhaps altered by a user. In this case, the assumption is that the intent is to aggregate data from one or more data sources in the DataTable, and then perhaps propagate the data back to the primary data source. The LoadOption parameter is used for determining the specific version of the row that is to be used for primary key comparison. The table below provides the details.

Load option

DataRow version used for primary key comparison

OverwriteChanges

Original version, if it exists, otherwise Current version

PreserveChanges

Original version, if it exists, otherwise Current version

Upsert

Current version, if it exists, otherwise Original version

The errorHandler parameter is a FillErrorEventHandler delegate that refers to a procedure that is called when an error occurs while loading data. The FillErrorEventArgs parameter passed to the procedure provides properties that allow you to retrieve information about the error that occurred, the current row of data, and the DataTable being filled. Using this delegate mechanism, rather than a simpler try/catch block, allows you to determine the error, handle the situation, and continue processing if you like. The FillErrorEventArgs parameter supplies a Continue property: set this property to true to indicate that you have handled the error and wish to continue processing. Set the property to false to indicate that you wish to halt processing. Be aware that setting the property to false causes the code that triggered the problem to throw an exception.

static void Main()
{
    // Attempt to load data from a data reader in which 
    // the schema is incompatible with the current schema. 
    // If you use exception handling, you won't get the chance 
    // to examine each row, and each individual table, 
    // as the Load method progresses. 
    // By taking advantage of the FillErrorEventHandler delegate, 
    // you can interact with the Load process as an error occurs, 
    // attempting to fix the problem, or simply continuing or quitting 
    // the Load process:
    DataTable table = GetIntegerTable();
    DataTableReader reader = new DataTableReader(GetStringTable());
    table.Load(reader, LoadOption.OverwriteChanges, FillErrorHandler);

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

private static DataTable GetIntegerTable()
{
    // Create sample Customers table, in order 
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(int));

    // Set the ID column as the primary key column.
    table.PrimaryKey = new DataColumn[] { idColumn };

    table.Rows.Add(new object[] { 4 });
    table.Rows.Add(new object[] { 5 });
    table.AcceptChanges();
    return table;
}

private static DataTable GetStringTable()
{
    // Create sample Customers table, in order 
    // to demonstrate the behavior of the DataTableReader.
    DataTable table = new DataTable();

    // Create two columns, ID and Name.
    DataColumn idColumn = table.Columns.Add("ID", typeof(string));

    // Set the ID column as the primary key column.
    table.PrimaryKey = new DataColumn[] { idColumn };

    table.Rows.Add(new object[] { "Mary" });
    table.Rows.Add(new object[] { "Andy" });
    table.Rows.Add(new object[] { "Peter" });
    table.AcceptChanges();
    return table;
}

static void FillErrorHandler(object sender, FillErrorEventArgs e)
{
    // You can use the e.Errors value to determine exactly what 
    // went wrong. 
    if (e.Errors.GetType() == typeof(System.FormatException))
    {
        Console.WriteLine("Error when attempting to update the value: {0}", 
            e.Values[0]);
    }

    // Setting e.Continue to True tells the Load 
    // method to continue trying. Setting it to False 
    // indicates that an error has occurred, and the  
    // Load method raises the exception that got  
    // you here.
    e.Continue = true;
}

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.