DataSet Class
Assembly: System.Data.dll
Represents an in-memory cache of data. A DataSet is a collection of tables (DataTables) that, when taken together, represents a complete set of data, including the relationships and constraints between them.
The DataSet can contain multiple tables, each with its own set of rows and columns. It also supports relationships between tables, allowing you to navigate between related data, and constraints to enforce data integrity.
Syntax
public class DataSet : MarshalByRefObject, System.Collections.ICloneable
Remarks
The DataSet is a fundamental component of ADO.NET, providing a disconnected, in-memory representation of data. It is particularly useful when working with databases, as it allows you to retrieve data, modify it, and then update the database without maintaining a continuous connection.
Key features of DataSet include:
- Collection of DataTables: A DataSet can contain zero or more DataTables.
- Relations: You can define relationships between DataTables within a DataSet, similar to foreign key relationships in a relational database.
- Constraints: DataSets support unique constraints and foreign key constraints to ensure data integrity.
- Xml Support: DataSets can be easily serialized to and deserialized from XML.
Members
Constructors
Name | Description |
---|---|
DataSet() |
Initializes a new instance of the DataSet class. |
DataSet(string datasetName) |
Initializes a new instance of the DataSet class with the specified name. |
Properties
Name | Description |
---|---|
CaseSensitive |
Gets or sets a value indicating whether table name comparisons are case sensitive. |
DataSetName |
Gets or sets the name of the DataSet. |
DefaultViewManager |
Gets a default ViewManager for the DataSet. |
EnforceConstraints |
Gets or sets a value indicating whether to enforce constraints. |
ExtendedProperties |
Gets a collection of custom user information for the DataSet. |
HasErrors |
Gets a value indicating whether any of the rows in any of the tables have errors. |
Locale |
Gets or sets the current culture information for the DataSet. |
Relations |
Gets a collection of DataRelations for this DataSet. |
SchemaSerializationMode |
Gets or sets the serialization mode for the DataSet schema. |
Tables |
Gets a collection of DataTables contained in the DataSet. |
Methods
Name | Description |
---|---|
AcceptChanges() |
Applies all the changes made since the last call to AcceptChanges or since the DataSet was created. |
BeginInit() |
Begins the initialization of a DataSet that is used by a form or component. |
Clone() |
Creates a new object that is a copy of the current instance. |
Clear() |
Removes all rows and any schema from the DataSet. |
Copy() |
Copies the structure of the DataSet, including all tables, relations, and constraints. |
EndInit() |
Ends the initialization of a DataSet that is used by a form or component. |
GetChanges() |
Returns a copy of the DataSet that contains all changes made to it since it was last loaded or AcceptChanges was called. |
LoadXml(string xmlString) |
Loads the DataSet from the specified XML string. |
Merge(DataSet dataSet) |
Merges the specified DataSet into this DataSet. |
ReadXml(string filename) |
Reads the XML content from the specified file and loads it into the DataSet. |
RejectChanges() |
Rolls back all changes made to the DataSet since the last call to AcceptChanges. |
Reset() |
Resets the DataSet to its initial state. |
Tables.Add(DataTable table) |
Adds a DataTable to the DataSet's Tables collection. |
WriteXml(string filename) |
Writes the XML content of the DataSet to the specified file. |
WriteXmlSchema(string filename) |
Writes the XML schema of the DataSet to the specified file. |
Constructors
DataSet()
public DataSet();
Initializes a new instance of the DataSet class. This constructor sets the default values for the properties of the DataSet.
DataSet(string datasetName)
public DataSet(string datasetName);
Initializes a new instance of the DataSet class with the specified name.
datasetName
- The name of the DataSet.
Properties
CaseSensitive
public bool CaseSensitive { get; set; }
Gets or sets a value indicating whether table name comparisons are case sensitive. If set to true
, table names are compared in a case-sensitive manner. If set to false
(the default), comparisons are case-insensitive.
DataSetName
public string DataSetName { get; set; }
Gets or sets the name of the DataSet. This name can be used to identify the DataSet when it is part of a collection or serialized.
DefaultViewManager
public System.ComponentModel.Design.DesigntimeLicenseContext DefaultViewManager { get; }
Gets a default ViewManager for the DataSet. The ViewManager provides a way to manage the default views for all tables within the DataSet.
EnforceConstraints
public bool EnforceConstraints { get; set; }
Gets or sets a value indicating whether to enforce constraints. If set to true
, the DataSet will enforce all defined constraints (e.g., unique constraints, foreign key constraints). If set to false
, constraint checking is disabled.
ExtendedProperties
public System.Collections.Properties ExtendedProperties { get; }
Gets a collection of custom user information for the DataSet. This property can be used to store arbitrary objects associated with the DataSet.
HasErrors
public bool HasErrors { get; }
Gets a value indicating whether any of the rows in any of the tables have errors. Returns true
if any row has an error, false
otherwise.
Locale
public System.Globalization.CultureInfo Locale { get; set; }
Gets or sets the current culture information for the DataSet. This affects string comparisons and sorting within the DataSet.
Relations
public RelatedCollection<DataRelation> Relations { get; }
Gets a collection of DataRelations for this DataSet. This collection allows you to access and manage the relationships defined between the DataTables within the DataSet.
SchemaSerializationMode
public System.Data.SchemaSerializationMode SchemaSerializationMode { get; set; }
Gets or sets the serialization mode for the DataSet schema. This property controls how the schema of the DataSet is serialized when writing to XML.
Tables
public DataTableCollection Tables { get; }
Gets a collection of DataTables contained in the DataSet. This is the primary way to access the individual tables within the DataSet.
Methods
AcceptChanges()
public void AcceptChanges();
Applies all the changes made since the last call to AcceptChanges
or since the DataSet was created. This method commits any pending additions, deletions, or modifications in all DataTables within the DataSet. Rows marked for deletion are removed, and modified rows are set to their original state.
BeginInit()
public void BeginInit();
Begins the initialization of a DataSet that is used by a form or component. This method is typically called by the design environment when initializing a control or component that uses a DataSet.
Clone()
public object Clone();
Creates a new object that is a copy of the current instance. The Clone
method creates a new DataSet with the same schema (tables, columns, relations, and constraints) as the original DataSet, but it does not copy the data. The returned object is of type object
and needs to be cast to DataSet
.
Clear()
public void Clear();
Removes all rows and any schema from the DataSet. This method effectively empties the DataSet, removing all DataTables and their data. The schema definition is also removed.
Copy()
public DataSet Copy();
Copies the structure of the DataSet, including all tables, relations, and constraints. This method creates a new DataSet that is a deep copy of the original DataSet's structure. It does not copy the data itself.
EndInit()
public void EndInit();
Ends the initialization of a DataSet that is used by a form or component. This method should be called after BeginInit
and any initialization code has completed.
GetChanges()
public DataSet GetChanges();
Returns a copy of the DataSet that contains all changes made to it since it was last loaded or AcceptChanges
was called. The returned DataSet will contain only the rows that have been added, deleted, or modified.
LoadXml(string xmlString)
public void LoadXml(string xmlString);
Loads the DataSet from the specified XML string. This method parses the XML string and populates the DataSet with the schema and data contained within the XML.
xmlString
- The XML string to load.
Merge(DataSet dataSet)
public void Merge(DataSet dataSet);
Merges the specified DataSet into this DataSet. Rows and tables from the source DataSet are merged into the current DataSet. If tables with the same name already exist, their rows are merged. Constraints and relations may also be merged or created.
dataSet
- The DataSet to merge.
ReadXml(string filename)
public void ReadXml(string filename);
Reads the XML content from the specified file and loads it into the DataSet. This method can load both the schema and the data from an XML file.
filename
- The path to the XML file.
RejectChanges()
public void RejectChanges();
Rolls back all changes made to the DataSet since the last call to AcceptChanges
. Any additions, deletions, or modifications will be discarded, and the DataSet will revert to its state before the changes were made.
Reset()
public void Reset();
Resets the DataSet to its initial state. This method removes all tables, relations, and constraints from the DataSet, effectively making it empty.
Tables.Add(DataTable table)
public void Tables.Add(DataTable table);
Adds a DataTable to the DataSet's Tables collection. The provided DataTable becomes part of the DataSet, and its schema, rows, and any associated metadata are now managed by the DataSet.
table
- The DataTable to add.
WriteXml(string filename)
public void WriteXml(string filename);
Writes the XML content of the DataSet to the specified file. This method serializes the DataSet's data into an XML format and saves it to the provided file path.
filename
- The path to the XML file to write.
WriteXmlSchema(string filename)
public void WriteXmlSchema(string filename);
Writes the XML schema of the DataSet to the specified file. This method serializes the schema definition of the DataSet (tables, columns, relations, constraints) into an XSD format and saves it to the provided file path.
filename
- The path to the XSD file to write.
Example
using System;
using System.Data;
public class DataSetExample
{
public static void Main(string[] args)
{
// Create a new DataSet
DataSet ds = new DataSet("MySampleDataSet");
// Create a DataTable
DataTable dt = new DataTable("Customers");
// Add columns to the DataTable
dt.Columns.Add("CustomerID", typeof(int));
dt.Columns.Add("CustomerName", typeof(string));
dt.Columns.Add("City", typeof(string));
// Set primary key
dt.PrimaryKey = new DataColumn[] { dt.Columns["CustomerID"] };
// Add rows to the DataTable
dt.Rows.Add(1, "Alfreds Futterkiste", "Berlin");
dt.Rows.Add(2, "Ana Trujillo Emparedados y helados", "Mexico D.F.");
dt.Rows.Add(3, "Antonio Moreno TaquerÃa", "Mexico D.F.");
// Add the DataTable to the DataSet
ds.Tables.Add(dt);
// You can now access the data
Console.WriteLine($"DataSet Name: {ds.DataSetName}");
Console.WriteLine($"Number of tables: {ds.Tables.Count}");
Console.WriteLine($"Table Name: {ds.Tables["Customers"].TableName}");
foreach (DataRow row in ds.Tables["Customers"].Rows)
{
Console.WriteLine($"ID: {row["CustomerID"]}, Name: {row["CustomerName"]}, City: {row["City"]}");
}
}
}