Ado. NET reading Notes series------DataSet object

Source: Internet
Author: User
Tags foreach object contains copy net reset return string
Ado| Notes | objects
First, the characteristics of the introduction

1. Working with offline data is useful in multi-tier applications.

2. You can view the contents of any row in the dataset at any time, allowing you to modify the method of query results.

3, Processing classification data

4. Cache changes

5. XML Integrity: DataSet objects and XML documents are almost interchangeable.

Second, the use of the introduction

1. Create DataSet object: DataSet ds = new DataSet ("DatasetName");

2. View the structure created by calling Sqldataadapter.fill

Da. Fill (ds, "Orders");

DataTable tbl = ds. TABLE[0];

foreach (DataColumn col in tbl. Columns)

Console.WriteLine (Col. ColumnName);

3, view the data returned by SqlDataAdapter

①, DataRow objects

DataTable tbl = ds. TABLE[0];

DataRow row = tbl. ROW[0];

Console.WriteLine (ros["OrderID"]);

②, checking the data stored in DataRow

DataTable tbl = row. Table;

foreach (DataColumn col in tbl. Columns)

Console.WriteLine (Row[col]);

③, checking for DataRow objects in dattable

foreach (DataRow row in tbl. Rows)

DisplayRow (row);

4, verify the data in the dataset

①, validating DataColumn properties: Readonly,allowdbnull,maxlength,unique

Constrains collection of ②, DataTable objects: Uiqueconstraints,primarykey,foreignkeyconstraints

It is not usually necessary to create a foreignkeyconstraints, because one is created when a relationship is created between the two DataTable objects in the dataset.

③, using Sqldataadapter.fill mode to retrieve schema information

5. Write code to create a DataTable object

①, creating DataTable objects: DataTable tbl = new DataTable ("TableName");

②, adding a DataTable to the table collection of a DataSet object

DataSet ds = new DataSet ();

DataTable tbl = new DataTable ("Customers");

Ds. Tables.add (TBL);

 

DataSet ds = new DataSet ();

DataTable tbl = ds. Tables.add ("Customers");

A DataTable object can exist only in at most one DataSet object. If you want to add a DataTable to multiple datasets, you must use either the Copy method or the Clone method. The Copy method creates a new Datatable;clone method that is the same as the original DataTable structure and contains peers, creating a new DataTable that is the same as the original DataTable structure but does not contain any rows.

③, adding columns for a DataTable

DataTable tbl = ds. Tables.add ("Orders");

DataColumn Col =tbl. Columns.Add ("OrderID", typeof (int));

Col. AllowDBNull = false;

Col. MaxLength = 5;

Col. Unique = true;

Tbl. PrimaryKey = new Datacolumn[]{tbl. columns["Customersid"]};

When the primary key is set, the AllowDBNull is automatically set to false;

④, processing AutoIncrement columns

DataSet ds = new DataSet ();

DataTable tbl = ds. Tables.add ("Orders");

DataColumn col = tbl. Columns.Add ("OrderID", typeof (int));

Col. AutoIncrement = true;

Col. AutoIncrementSeed =-1;

Col. AutoIncrementStep =-1;

Col. ReadOnly = true;

⑤, adding a column based on an expression

Tbl. Columns.Add ("Itemtotal", typeof (Decimal), "Quantity*unitprice");

6, modify the contents of the DataTable

①, add new DataRow

DataRow row = ds. tables["Customers"]. NewRow ();

row["CustomerID"] = "ALFKI";

Ds. tables["Customers"]. Rows.Add (row);

 

Object[] avalues ={"ALFKI", "Alfreds", "Anders", "030-22222"};

Da. tables["Customers"]. Loaddatarow (Avalues,false);

②, modifying when moving forward

Modify the contents of the row the contents of the database are not automatically modified in the confession, and the modifications made to the row are considered to be subsequent use of the SqlDataAdapter object to submit pending changes to the database.

DataRow Rowcustomer;

Rowcustomer = ds. tables["Custoemrs"]. Rows.find ("ANTON");

if (Rowcustomer = null)

No customer found

Else

{

rowcustomer["CompanyName"] = "newcompanyname";

rowcustomer["ContactName"] = "newcontactname";

}

 

It is recommended to use this method

DataRow Rowcustomer;

Rowcustomer = ds. tables["Custoemrs"]. Rows.find ("ANTON");

if (Rowcustomer = null)

No customer found

Else

{

Rowcustomer.beginedit ();

rowcustomer["CompanyName"] = "newcompanyname";

rowcustomer["ContactName"] = "newcontactname";

Rowcustomer.endedit ();

}

 

Null indicates that the data for this column is not modified

Obejct[] Acustomer ={null, "Newcompanyname", "Newcontactname", null}

DataRow Rowcustomer;

Rowcustomer = ds. tables["Customers"]. Rows.find ("ALFKI");

Rowcustomer.itemarray = Acustomer;

③, handling null values of DataRow

To see if it is empty

DataRow Rowcustomer;

Rowcustomer = ds. tables["Customers"]. Rows.find ("ALFKI");

if (Rowcustomer.isnull ("Phone"))

Console.WriteLine ("It ' s Null");

Else

Console.WriteLine ("It ' s not Null");

 

Give null value

rowcustomer["Phone"] = DBNull.Value;

④, delete DataRow

DataRow Rowcustomer;

Rowcustomer = ds. tables["Customers"]. Rows.find ("ALFKI");

Rowcustomer.delete ();

⑤, Clear DataRow

DataRow Rowcustomer = ds. tables["Customers"]. Rows.find ("ALFKI");

Rowcustomer.itemarray = Acustomer;

Da. tables["Customers"]. Remove (Rowcustomer);

Or

Ds. tables["Customers"]. RemoveAt (Intindex);

⑥, using Datarow.rowstate properties: unchanged,detached,added,modified,deleted

private void Demonstraterowstate ()

{
Run a function to create a DataTable with one column.
DataTable myTable = maketable ();
DataRow Myrow;

Create a new DataRow.
Myrow = Mytable.newrow ();
Detached row.
Console.WriteLine ("New Row" + myrow.rowstate);

MYTABLE.ROWS.ADD (Myrow);
New row.
Console.WriteLine ("AddRow" + myrow.rowstate);

Mytable.acceptchanges ();
Unchanged row.
Console.WriteLine ("AcceptChanges" + myrow.rowstate);

myrow["FirstName"] = "Scott";
Modified row.
Console.WriteLine ("Modified" + myrow.rowstate);

Myrow.delete ();
Deleted row.
Console.WriteLine ("Deleted" + myrow.rowstate);
}

⑦, checking for pending changes in DataRow

DataRow Rowcustomer;

Rowcustomer = ds. tables["Customers"]. Rows.find ("ALFKI");

rowcustomer["CompanyName"] = "newcompanyname";

String Strnewcompanyname,stroldcompanyname;

Console.WriteLine (rowcustomer["CompanyName", datarowversion.current));

Console.WriteLine (rowcustomer["CompanyName", DataRowVersion.Original));

Introduction of Property Method events

1. DataSet

①, properties

CaseSensitive: Used to control whether string comparisons in a DataTable are case-sensitive.

DatasetName: The name of the current dataset. If not specified, the property value is set to "NewDataSet". If you write the dataset content to an XML file, DatasetName is the root node name of the XML file.

DesignMode: False If you return true at design time using Dataset,designmode in the component.

HasErrors: Indicates whether the DataRow object in the dataset contains errors. If you submit a batch of changes to the database and set the ContinueUpdateOnError property of the DataAdapter object to True, you must check the HasErrors property of the dataset after the change is committed to determine if an update failed.

namespace and prefix: Specifying XML namespaces and prefixes

Relations: Returns a DataRelationCollection object.

Tables: Check for existing DataTable objects. The ability to access the DataTable through the index is better.

②, methods

AcceptChanges and RejectChanges: Accept or discard all pending changes in the dataset. When AcceptChanges is invoked, the RowState property for all rows of the RowState property value added or modified is set to unchanged. Any deleted object marked as DataRow will be deleted from the dataset. When RejectChanges is invoked, any DataRow object marked as added will be deleted from the dataset, and the other modified Datrow object will return to the previous state.

Clear: Clears all DataRow objects in the dataset. This method is faster than releasing a dataset and then creating a new dataset of the same structure.

Clone and copy: Use the Copy method to create a new dataset with the same structure and rows as the original dataset. Using the Clone method creates a new dataset with the same structure, but does not contain any rows.

GetChanges: Returns a new dataset with the same structure as the original DataSet object, and also contains the rows of all pending changes in the original dataset.

Getxml and GetXmlSchema: Use the Getxml method to get the contents of the dataset and her schema information converted to XML-formatted strings. If you only want to return schema information, you can use GetXmlSchema.

Haschange: Represents the DataRow object that contains pending changes in the dataset.

Merge: Loads data from another dataset, DataTable, or a set of DataRow objects in an existing dataset.

ReadXml and WriteXml: Use the ReadXml method to load XML data into a dataset from files, TextReader, data streams, or XmlReader.

Reset: Returns the DataSet to an uninitialized state. If you want to discard an existing dataset and start processing a new dataset, it is better to use the Reset method than to create a new instance of a dataset.

③, Events

MergeFailed: Triggered when an exception occurs in the dataset's Merge method.

2. DataTable

①, properties

②, methods

③, Events

ColumnChanged: Triggered after the contents of the column have been changed

Columnchangding: Triggers before the contents of the column are changed

Rowchanged,rowchanging,rowdeleted,rowdeleting.

3, DataColumn

①, properties

4, DataRow

①, properties

Haserror: Determines whether the row contains errors.

Item: Accesses the contents of a column by specifying the number of columns in the row, the name of the column, or the DataColumn object itself.

ItemArray: Gets or sets the value of all the columns in the row.

RowError: Returns a string containing the row error message.

RowState: Returns the value in the DataRowState enumeration to represent the current state of the row.

Table: Returns the DataTable where the DataRow object resides.

②, methods

AcceptChanges and RejectChanges: Commit and discard pending changes.

BeginEdit, CancelEdit, EndEdit

Clearerrors: Clears all errors in the DataRow.

The Delete:delete method does not actually remove the DataRow from the row collection of the DataRow table. When you call the DataRow object's Delete method, ADO. NET marks the row as deleted, and then calls the SqlDataAdapter object's Update method to delete its corresponding row in the database.

If you want to completely remove DataRow, you can call the Delete method, then call its Acceptechanges method, and you can do the same task using the DataRowCollection object's Remove method.

 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.