แก้ไข

แชร์ผ่าน


DataSet Class

Definition

Represents an in-memory cache of data.

public ref class DataSet : System::ComponentModel::MarshalByValueComponent, System::ComponentModel::IListSource, System::ComponentModel::ISupportInitialize, System::ComponentModel::ISupportInitializeNotification, System::Runtime::Serialization::ISerializable, System::Xml::Serialization::IXmlSerializable
public ref class DataSet : System::ComponentModel::MarshalByValueComponent, System::ComponentModel::IListSource, System::ComponentModel::ISupportInitialize, System::Runtime::Serialization::ISerializable, System::Xml::Serialization::IXmlSerializable
public ref class DataSet : System::ComponentModel::MarshalByValueComponent, System::ComponentModel::IListSource, System::ComponentModel::ISupportInitializeNotification, System::Runtime::Serialization::ISerializable, System::Xml::Serialization::IXmlSerializable
public class DataSet : System.ComponentModel.MarshalByValueComponent, System.ComponentModel.IListSource, System.ComponentModel.ISupportInitialize, System.ComponentModel.ISupportInitializeNotification, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable
[System.Serializable]
public class DataSet : System.ComponentModel.MarshalByValueComponent, System.ComponentModel.IListSource, System.ComponentModel.ISupportInitialize, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable
[System.Serializable]
public class DataSet : System.ComponentModel.MarshalByValueComponent, System.ComponentModel.IListSource, System.ComponentModel.ISupportInitializeNotification, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable
public class DataSet : System.ComponentModel.MarshalByValueComponent, System.ComponentModel.IListSource, System.ComponentModel.ISupportInitializeNotification, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable
type DataSet = class
    inherit MarshalByValueComponent
    interface IListSource
    interface ISupportInitialize
    interface ISupportInitializeNotification
    interface ISerializable
    interface IXmlSerializable
[<System.Serializable>]
type DataSet = class
    inherit MarshalByValueComponent
    interface IListSource
    interface IXmlSerializable
    interface ISupportInitialize
    interface ISerializable
[<System.Serializable>]
type DataSet = class
    inherit MarshalByValueComponent
    interface IListSource
    interface IXmlSerializable
    interface ISupportInitializeNotification
    interface ISupportInitialize
    interface ISerializable
Public Class DataSet
Inherits MarshalByValueComponent
Implements IListSource, ISerializable, ISupportInitialize, ISupportInitializeNotification, IXmlSerializable
Public Class DataSet
Inherits MarshalByValueComponent
Implements IListSource, ISerializable, ISupportInitialize, IXmlSerializable
Public Class DataSet
Inherits MarshalByValueComponent
Implements IListSource, ISerializable, ISupportInitializeNotification, IXmlSerializable
Inheritance
Attributes
Implements

Examples

The following example consists of several methods that, combined, create and fill a DataSet from the Northwind database.

using System;
using System.Data;
using System.Data.SqlClient;

namespace Microsoft.AdoNet.DataSetDemo
{
    class NorthwindDataSet
    {
        static void Main()
        {
            string connectionString = GetConnectionString();
            ConnectToData(connectionString);
        }

        private static void ConnectToData(string connectionString)
        {
            //Create a SqlConnection to the Northwind database.
            using (SqlConnection connection =
                       new SqlConnection(connectionString))
            {
                //Create a SqlDataAdapter for the Suppliers table.
                SqlDataAdapter adapter = new SqlDataAdapter();

                // A table mapping names the DataTable.
                adapter.TableMappings.Add("Table", "Suppliers");

                // Open the connection.
                connection.Open();
                Console.WriteLine("The SqlConnection is open.");

                // Create a SqlCommand to retrieve Suppliers data.
                SqlCommand command = new SqlCommand(
                    "SELECT SupplierID, CompanyName FROM dbo.Suppliers;",
                    connection);
                command.CommandType = CommandType.Text;

                // Set the SqlDataAdapter's SelectCommand.
                adapter.SelectCommand = command;

                // Fill the DataSet.
                DataSet dataSet = new DataSet("Suppliers");
                adapter.Fill(dataSet);

                // Create a second Adapter and Command to get
                // the Products table, a child table of Suppliers.
                SqlDataAdapter productsAdapter = new SqlDataAdapter();
                productsAdapter.TableMappings.Add("Table", "Products");

                SqlCommand productsCommand = new SqlCommand(
                    "SELECT ProductID, SupplierID FROM dbo.Products;",
                    connection);
                productsAdapter.SelectCommand = productsCommand;

                // Fill the DataSet.
                productsAdapter.Fill(dataSet);

                // Close the connection.
                connection.Close();
                Console.WriteLine("The SqlConnection is closed.");

                // Create a DataRelation to link the two tables
                // based on the SupplierID.
                DataColumn parentColumn =
                    dataSet.Tables["Suppliers"].Columns["SupplierID"];
                DataColumn childColumn =
                    dataSet.Tables["Products"].Columns["SupplierID"];
                DataRelation relation =
                    new System.Data.DataRelation("SuppliersProducts",
                    parentColumn, childColumn);
                dataSet.Relations.Add(relation);
                Console.WriteLine(
                    "The {0} DataRelation has been created.",
                    relation.RelationName);
            }
        }

        static private string GetConnectionString()
        {
            // To avoid storing the connection string in your code,
            // you can retrieve it from a configuration file.
            return "Data Source=(local);Initial Catalog=Northwind;"
                + "Integrated Security=SSPI";
        }
    }
}
Option Explicit On
Option Strict On

Imports System.Data
Imports system.Data.SqlClient

Public Class NorthwindDataSet

    Public Shared Sub Main()
        Dim connectionString As String = _
            GetConnectionString()
        ConnectToData(connectionString)
    End Sub

    Private Shared Sub ConnectToData( _
        ByVal connectionString As String)

        ' Create a SqlConnection to the Northwind database.
        Using connection As SqlConnection = New SqlConnection( _
           connectionString)

            ' Create a SqlDataAdapter for the Suppliers table.
            Dim suppliersAdapter As SqlDataAdapter = _
               New SqlDataAdapter()

            ' A table mapping names the DataTable.
            suppliersAdapter.TableMappings.Add("Table", "Suppliers")

            ' Open the connection.
            connection.Open()
            Console.WriteLine("The SqlConnection is open.")

            ' Create a SqlCommand to retrieve Suppliers data.
            Dim suppliersCommand As New SqlCommand( _
               "SELECT SupplierID, CompanyName FROM dbo.Suppliers;", _
               connection)
            suppliersCommand.CommandType = CommandType.Text

            ' Set the SqlDataAdapter's SelectCommand.
            suppliersAdapter.SelectCommand = suppliersCommand

            ' Fill the DataSet.
            Dim dataSet As New DataSet("Suppliers")
            suppliersAdapter.Fill(dataSet)

            ' Create a second SqlDataAdapter and SqlCommand to get
            ' the Products table, a child table of Suppliers. 
            Dim productsAdapter As New SqlDataAdapter()
            productsAdapter.TableMappings.Add("Table", "Products")

            Dim productsCommand As New SqlCommand( _
               "SELECT ProductID, SupplierID FROM dbo.Products;", _
               connection)
            productsAdapter.SelectCommand = productsCommand

            ' Fill the DataSet.
            productsAdapter.Fill(dataSet)

            ' Close the connection.
            connection.Close()
            Console.WriteLine("The SqlConnection is closed.")

            ' Create a DataRelation to link the two tables
            ' based on the SupplierID.
            Dim parentColumn As DataColumn = _
               dataSet.Tables("Suppliers").Columns("SupplierID")
            Dim childColumn As DataColumn = _
               dataSet.Tables("Products").Columns("SupplierID")
            Dim relation As New DataRelation("SuppliersProducts", _
               parentColumn, childColumn)
            dataSet.Relations.Add(relation)

            Console.WriteLine( _
               "The {0} DataRelation has been created.", _
               relation.RelationName)
        End Using

    End Sub

    Private Shared Function GetConnectionString() As String
        ' To avoid storing the connection string in your code,  
        ' you can retrieve it from a configuration file.
        Return "Data Source=(local);Initial Catalog=Northwind;" _
           & "Integrated Security=SSPI;"
    End Function
End Class

Remarks

For more information about this API, see Supplemental API remarks for DataSet.

Constructors

DataSet()

Initializes a new instance of the DataSet class.

DataSet(SerializationInfo, StreamingContext, Boolean)
Obsolete.

Initializes a new instance of the DataSet class with serialized data.

DataSet(SerializationInfo, StreamingContext)
Obsolete.

Initializes a new instance of the DataSet class with serialized data.

DataSet(String)

Initializes a new instance of the DataSet class with the given name.

Properties

CaseSensitive

Gets or sets a value indicating whether string comparisons within DataTable objects are case-sensitive.

Container

Gets the container for the component.

(Inherited from MarshalByValueComponent)
DataSetName

Gets or sets the name of the current DataSet.

DefaultViewManager

Gets a custom view of the data contained in the DataSet to allow filtering, searching, and navigating using a custom DataViewManager.

DesignMode

Gets a value indicating whether the component is currently in design mode.

(Inherited from MarshalByValueComponent)
EnforceConstraints

Gets or sets a value indicating whether constraint rules are followed when attempting any update operation.

Events

Gets the list of event handlers that are attached to this component.

(Inherited from MarshalByValueComponent)
ExtendedProperties

Gets the collection of customized user information associated with the DataSet.

HasErrors

Gets a value indicating whether there are errors in any of the DataTable objects within this DataSet.

IsInitialized

Gets a value that indicates whether the DataSet is initialized.

Locale

Gets or sets the locale information used to compare strings within the table.

Namespace

Gets or sets the namespace of the DataSet.

Prefix

Gets or sets an XML prefix that aliases the namespace of the DataSet.

Relations

Gets the collection of relations that link tables and allow navigation from parent tables to child tables.

RemotingFormat

Gets or sets the serialization format for the DataSet that's used during remoting.

SchemaSerializationMode

Gets or sets a SchemaSerializationMode for a DataSet.

Site

Gets or sets an ISite for the DataSet.

Tables

Gets the collection of tables contained in the DataSet.

Methods

AcceptChanges()

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

BeginInit()

Begins the initialization of a DataSet that is used on a form or used by another component. The initialization occurs at run time.

Clear()

Clears the DataSet of any data by removing all rows in all tables.

Clone()

Copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.

Copy()

Copies both the structure and data for this DataSet.

CreateDataReader()

Returns a DataTableReader with one result set per DataTable, in the same sequence as the tables appear in the Tables collection.

CreateDataReader(DataTable[])

Returns a DataTableReader with one result set per DataTable.

DetermineSchemaSerializationMode(SerializationInfo, StreamingContext)

Determines the SchemaSerializationMode for a DataSet.

DetermineSchemaSerializationMode(XmlReader)

Determines the SchemaSerializationMode for a DataSet.

Dispose()

Releases all resources used by the MarshalByValueComponent.

(Inherited from MarshalByValueComponent)
Dispose(Boolean)

Releases the unmanaged resources used by the MarshalByValueComponent and optionally releases the managed resources.

(Inherited from MarshalByValueComponent)
EndInit()

Ends the initialization of a DataSet that is used on a form or used by another component. The initialization occurs at run time.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetChanges()

Gets a copy of the DataSet that contains all changes made to it since it was loaded or since AcceptChanges() was last called.

GetChanges(DataRowState)

Gets a copy of the DataSet containing all changes made to it since it was last loaded, or since AcceptChanges() was called, filtered by DataRowState.

GetDataSetSchema(XmlSchemaSet)

Gets a copy of XmlSchemaSet for the DataSet.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext)
Obsolete.

Populates a serialization information object with the data needed to serialize the DataSet.

GetSchemaSerializable()

Returns a serializable XmlSchema instance.

GetSerializationData(SerializationInfo, StreamingContext)

Deserializes the table data from the binary or XML stream.

GetService(Type)

Gets the implementer of the IServiceProvider.

(Inherited from MarshalByValueComponent)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
GetXml()

Returns the XML representation of the data stored in the DataSet.

GetXmlSchema()

Returns the XML Schema for the XML representation of the data stored in the DataSet.

HasChanges()

Gets a value indicating whether the DataSet has changes, including new, deleted, or modified rows.

HasChanges(DataRowState)

Gets a value indicating whether the DataSet has changes, including new, deleted, or modified rows, filtered by DataRowState.

InferXmlSchema(Stream, String[])

Applies the XML schema from the specified Stream to the DataSet.

InferXmlSchema(String, String[])

Applies the XML schema from the specified file to the DataSet.

InferXmlSchema(TextReader, String[])

Applies the XML schema from the specified TextReader to the DataSet.

InferXmlSchema(XmlReader, String[])

Applies the XML schema from the specified XmlReader to the DataSet.

InitializeDerivedDataSet()

Deserialize all of the tables data of the DataSet from the binary or XML stream.

IsBinarySerialized(SerializationInfo, StreamingContext)

Inspects the format of the serialized representation of the DataSet.

Load(IDataReader, LoadOption, DataTable[])

Fills a DataSet with values from a data source using the supplied IDataReader, using an array of DataTable instances to supply the schema and namespace information.

Load(IDataReader, LoadOption, FillErrorEventHandler, DataTable[])

Fills a DataSet with values from a data source using the supplied IDataReader, using an array of DataTable instances to supply the schema and namespace information.

Load(IDataReader, LoadOption, String[])

Fills a DataSet with values from a data source using the supplied IDataReader, using an array of strings to supply the names for the tables within the DataSet.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
Merge(DataRow[], Boolean, MissingSchemaAction)

Merges an array of DataRow objects into the current DataSet, preserving or discarding changes in the DataSet and handling an incompatible schema according to the given arguments.

Merge(DataRow[])

Merges an array of DataRow objects into the current DataSet.

Merge(DataSet, Boolean, MissingSchemaAction)

Merges a specified DataSet and its schema with the current DataSet, preserving or discarding changes in the current DataSet and handling an incompatible schema according to the given arguments.

Merge(DataSet, Boolean)

Merges a specified DataSet and its schema into the current DataSet, preserving or discarding any changes in this DataSet according to the given argument.

Merge(DataSet)

Merges a specified DataSet and its schema into the current DataSet.

Merge(DataTable, Boolean, MissingSchemaAction)

Merges a specified DataTable and its schema into the current DataSet, preserving or discarding changes in the DataSet and handling an incompatible schema according to the given arguments.

Merge(DataTable)

Merges a specified DataTable and its schema into the current DataSet.

OnPropertyChanging(PropertyChangedEventArgs)

Raises the OnPropertyChanging(PropertyChangedEventArgs) event.

OnRemoveRelation(DataRelation)

Occurs when a DataRelation object is removed from a DataTable.

OnRemoveTable(DataTable)

Occurs when a DataTable is removed from a DataSet.

RaisePropertyChanging(String)

Sends a notification that the specified DataSet property is about to change.

ReadXml(Stream, XmlReadMode)

Reads XML schema and data into the DataSet using the specified Stream and XmlReadMode.

ReadXml(Stream)

Reads XML schema and data into the DataSet using the specified Stream.

ReadXml(String, XmlReadMode)

Reads XML schema and data into the DataSet using the specified file and XmlReadMode.

ReadXml(String)

Reads XML schema and data into the DataSet using the specified file.

ReadXml(TextReader, XmlReadMode)

Reads XML schema and data into the DataSet using the specified TextReader and XmlReadMode.

ReadXml(TextReader)

Reads XML schema and data into the DataSet using the specified TextReader.

ReadXml(XmlReader, XmlReadMode)

Reads XML schema and data into the DataSet using the specified XmlReader and XmlReadMode.

ReadXml(XmlReader)

Reads XML schema and data into the DataSet using the specified XmlReader.

ReadXmlSchema(Stream)

Reads the XML schema from the specified Stream into the DataSet.

ReadXmlSchema(String)

Reads the XML schema from the specified file into the DataSet.

ReadXmlSchema(TextReader)

Reads the XML schema from the specified TextReader into the DataSet.

ReadXmlSchema(XmlReader)

Reads the XML schema from the specified XmlReader into the DataSet.

ReadXmlSerializable(XmlReader)

Ignores attributes and returns an empty DataSet.

RejectChanges()

Rolls back all the changes made to the DataSet since it was created, or since the last time AcceptChanges() was called.

Reset()

Clears all tables and removes all relations, foreign constraints, and tables from the DataSet. Subclasses should override Reset() to restore a DataSet to its original state.

ShouldSerializeRelations()

Gets a value indicating whether Relations property should be persisted.

ShouldSerializeTables()

Gets a value indicating whether Tables property should be persisted.

ToString()

Returns a String containing the name of the Component, if any. This method should not be overridden.

(Inherited from MarshalByValueComponent)
WriteXml(Stream, XmlWriteMode)

Writes the current data, and optionally the schema, for the DataSet using the specified Stream and XmlWriteMode. To write the schema, set the value for the mode parameter to WriteSchema.

WriteXml(Stream)

Writes the current data for the DataSet using the specified Stream.

WriteXml(String, XmlWriteMode)

Writes the current data, and optionally the schema, for the DataSet to the specified file using the specified XmlWriteMode. To write the schema, set the value for the mode parameter to WriteSchema.

WriteXml(String)

Writes the current data for the DataSet to the specified file.

WriteXml(TextWriter, XmlWriteMode)

Writes the current data, and optionally the schema, for the DataSet using the specified TextWriter and XmlWriteMode. To write the schema, set the value for the mode parameter to WriteSchema.

WriteXml(TextWriter)

Writes the current data for the DataSet using the specified TextWriter.

WriteXml(XmlWriter, XmlWriteMode)

Writes the current data, and optionally the schema, for the DataSet using the specified XmlWriter and XmlWriteMode. To write the schema, set the value for the mode parameter to WriteSchema.

WriteXml(XmlWriter)

Writes the current data for the DataSet to the specified XmlWriter.

WriteXmlSchema(Stream, Converter<Type,String>)

Writes the DataSet structure as an XML schema to the specified Stream object.

WriteXmlSchema(Stream)

Writes the DataSet structure as an XML schema to the specified Stream object.

WriteXmlSchema(String, Converter<Type,String>)

Writes the DataSet structure as an XML schema to a file.

WriteXmlSchema(String)

Writes the DataSet structure as an XML schema to a file.

WriteXmlSchema(TextWriter, Converter<Type,String>)

Writes the DataSet structure as an XML schema to the specified TextWriter.

WriteXmlSchema(TextWriter)

Writes the DataSet structure as an XML schema to the specified TextWriter object.

WriteXmlSchema(XmlWriter, Converter<Type,String>)

Writes the DataSet structure as an XML schema to the specified XmlWriter.

WriteXmlSchema(XmlWriter)

Writes the DataSet structure as an XML schema to an XmlWriter object.

Events

Disposed

Adds an event handler to listen to the Disposed event on the component.

(Inherited from MarshalByValueComponent)
Initialized

Occurs after the DataSet is initialized.

MergeFailed

Occurs when a target and source DataRow have the same primary key value, and EnforceConstraints is set to true.

Explicit Interface Implementations

IListSource.ContainsListCollection

For a description of this member, see ContainsListCollection.

IListSource.GetList()

For a description of this member, see GetList().

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Populates a serialization information object with the data needed to serialize the DataSet.

IXmlSerializable.GetSchema()

For a description of this member, see GetSchema().

IXmlSerializable.ReadXml(XmlReader)

For a description of this member, see ReadXml(XmlReader).

IXmlSerializable.WriteXml(XmlWriter)

For a description of this member, see WriteXml(XmlWriter).

Extension Methods

GetKeyedService<T>(IServiceProvider, Object)

Get service of type T from the IServiceProvider.

GetKeyedServices(IServiceProvider, Type, Object)

Get an enumeration of services of type serviceType from the IServiceProvider.

GetKeyedServices<T>(IServiceProvider, Object)

Get an enumeration of services of type T from the IServiceProvider.

GetRequiredKeyedService(IServiceProvider, Type, Object)

Get service of type serviceType from the IServiceProvider.

GetRequiredKeyedService<T>(IServiceProvider, Object)

Get service of type T from the IServiceProvider.

CreateAsyncScope(IServiceProvider)

Creates a new AsyncServiceScope that can be used to resolve scoped services.

CreateScope(IServiceProvider)

Creates a new IServiceScope that can be used to resolve scoped services.

GetRequiredService(IServiceProvider, Type)

Get service of type serviceType from the IServiceProvider.

GetRequiredService<T>(IServiceProvider)

Get service of type T from the IServiceProvider.

GetService<T>(IServiceProvider)

Get service of type T from the IServiceProvider.

GetServices(IServiceProvider, Type)

Get an enumeration of services of type serviceType from the IServiceProvider.

GetServices<T>(IServiceProvider)

Get an enumeration of services of type T from the IServiceProvider.

GetFakeLogCollector(IServiceProvider)

Gets the object that collects log records sent to the fake logger.

GetFakeRedactionCollector(IServiceProvider)

Gets the fake redactor collector instance from the dependency injection container.

Applies to

Thread Safety

This type is safe for multithreaded read operations. You must synchronize any write operations.

See also