Upload
aspnet123
View
546
Download
0
Embed Size (px)
Citation preview
USING ADO.NET DISCONNECTED
CLASSES
Disconnected Data Classes
DataTable DataColumn DataRow DataView DataSet
Getting Started with DataTable
The DataTable object represents tabular data as rows, columns, and constraints.
Use the DataTable object to hold data in memory while performing disconnected data operations.
Can get a DataTable object by connecting to the database and returning table data.
Creating DataTable
Can be explicitly created by instantiating the DataTable class
You then add DataColumn objects to the class to define the type of data to be held.
The DataColumn objects also contain constraints.
Once the DataTable is defined with columns, you can add DataRow objects that contain data for the table.
Creating DataTable
private DataTable GetDataTable(){
DataTable employee = new DataTable("Employee");
DataColumn eid = new DataColumn("Eid");eid.DataType = typeof(string);eid.MaxLength = 10;eid.Unique = true;eid.AllowDBNull = false;eid.Caption = "EID";employee.Columns.Add(eid);return employee;
}
DataColumn Properties
DataType MaxLength Unique AllowDBNull Caption
Creating Primary Key Columns
The primary key of a DataTable object consists of one or more columns that define data that represent a unique identity for each row in the data.
employee.PrimaryKey = new DataColumn[] {eid};
Adding Data with DataRow Objects
The DataTable object contains a Rows collection, which contains a collection of DataRow objects.
You can insert data into the Rows collection by using
Add method on the Rows collection Load method on the DataTable object.
Adding Data using Add Method
DataRow newemployee = employee.NewRow();newemployee["Eid"] = "123456789A";newemployee["FirstName"] = "Nancy";newemployee["LastName"] = "Davolio";newemployee["Salary"] = 10.00m;employee.Rows.Add(newemployee);
Or
employee.Rows.Add("987654321X", "Andrew", "Fuller", 15.00m);
Adding Data using Load Method
employee.LoadDataRow( new object[] { "987654321X", "Janet", "Leverling",
20.00m },LoadOption.OverwriteChanges);
LoadOption enumeration value that has one of the following values:
OverwriteChanges PreserveChanges Upsert
DataRowStates
Detached : DataRow is created but not added to a DataTable.
Added : DataRow is added to a DataTable. Unchanged : DataRow has not changed
since the last call to the AcceptChanges method. The DataRow changes to this state when the AcceptChanges method is called.
Modified : DataRow has been modified since the last time the AcceptChanges method was called.
Deleted : DataRow is deleted using the Delete method of the DataRow.
DataRowStates
DataRow States The AcceptChanges method is used to reset the
DataRow state to Unchanged.
After data has been loaded from the database, the RowState property of the loaded rows is set to Added.
Calling AcceptChanges on the DataTable resets the RowState of all of the DataRow objects to Unchanged.
If you modify the DataRow objects, their RowState changes to Modified.
After the changes have been successfully sent to the data store by calling the AcceptChanges method the RowState changes to Unchanged.
Deleting and Undeleting the DataRow
The Delete method on the DataRow is used to set the RowState of the DataRow to Deleted.
There are many scenarios where you need to undelete a DataRow.
The DataRow object doesn’t have an undelete method, but you can use the RejectChanges method to perform an undelete that may satisfy some scenarios.
DataRowVersion The DataRow object can hold up to three versions, or
copies, of the data: Original, Current, and Proposed.
When the DataRow is created, it contains a single copy of the data, which is the Current version.
When the DataRow is placed into edit mode by executing its BeginEdit method, changes to the data are placed in a second version of the data, called the Proposed version.
When the EndEdit method is executed, the Current version becomes the Original version, the Proposed version becomes the Current version, and the Proposed version no longer exists.
After EndEdit has completed its execution, there are two
versions of the DataRow data: Original and Current.
Copying and Cloning the DataTable
You often need to create a full copy of a DataTable in your application.
For example, you might want to assign a DataTable object to a GridView control to allow a user to edit the data, but you also might want to provide a cancel button that aborts all changes on the Web page.
A simple way to implement this functionality is to create a copy of your DataTable object and use the copy for editing.
DataTable copy = employee.Copy();
Copying and Cloning the DataTable
You often require a copy of the DataTable schema without the data.
You can accomplish this by invoking the Clone method on the DataTable.
Use this method when an empty copy of the DataTable is required and to which DataRow objects will be added at a later time.
DataTable clone = employee.Clone();clone.ImportRow(employee.Rows[0]);
The ImportRow method on the DataTable object copies a DataRow from a DataTable that has the same schema.
DataView The DataView object provides a window into a
DataTable that can be sorted and filtered using the Sort, RowFilter, and RowStateFilter properties.
A DataTable can have many DataView objects assigned to it, allowing the data to be viewed in many different ways without requiring the data to be reread from the database.
The DataView object also contains the AllowDelete, AllowEdit, and AllowNew properties to constrain user input as needed.
DataViewprotected void Button7_Click(object sender, EventArgs
e){//get datatableDataTable employee = GetDataTable();//sort and displayDataView view = new DataView(employee);view.Sort = "LastName ASC, FirstName ASC, Salary
DESC";GridView1.DataSource = view;GridView1.DataBind();}Also RowFilter can be set to a SQL WHERE clause
without the word “WHERE.”view.RowFilter = "LastName like 'A%' and Salary >
15";
DataSet The DataSet is a memory-based relational
representation of data and the primary disconnected data object.
The DataSet contains a collection of DataTable and DataRelation objects.
DataSetprivate DataSet GetDataSet(){DataSet companyData = new DataSet("CompanyList");DataTable company = companyData.Tables.Add("company");company.Columns.Add("Id", typeof(Guid));company.Columns.Add("CompanyName", typeof(string));company.PrimaryKey = new DataColumn[]
{ company.Columns["Id"] };DataTable employee = companyData.Tables.Add("employee");employee.Columns.Add("Id", typeof(Guid));employee.Columns.Add("companyId", typeof(Guid));employee.Columns.Add("LastName", typeof(string));employee.Columns.Add("FirstName", typeof(string));employee.Columns.Add("Salary", typeof(decimal));employee.PrimaryKey = new DataColumn[]
{ employee.Columns["Id"] };companyData.Relations.Add("Company_Employee",company.Columns["Id"],employee.Columns["CompanyId"]);return companyData;}
Navigating DataTable Objects with DataRelation Objects
Label lbl = GetLabel(275, 20);DataSet companyList = GetDataSet();DataRelation dr = companyList.Relations["Company_Employee"];DataRow companyParent = companyList.Tables["company"].Rows[1];lbl.Text = companyParent["CompanyName"] + "<br />";foreach (DataRow employeeChild in
companyParent.GetChildRows(dr)){lbl.Text += " " + employeeChild["Id"] + " "+ employeeChild["LastName"] + " "+ employeeChild["FirstName"] + " "+ string.Format("{0:C}", employeeChild["Salary"]) + "<br />";}lbl.Text += "<br /><br />";DataRow employeeParent =
companyList.Tables["employee"].Rows[1];lbl.Text += employeeParent["Id"] + " "+ employeeParent["LastName"] + " "+ employeeParent["FirstName"] + " "+ string.Format("{0:C}", employeeParent["Salary"]) + "<br />";DataRow companyChild = employeeParent.GetParentRow(dr);lbl.Text += " " +
companyChild["CompanyName"] + "<br />";
Serializing and Deserializing DataSet Objects
A DataSet can be serialized as XML or as binary data to a stream or file.
The DataSet can also be deserialized from XML or binary data from a stream or file. The serialized data can be transferred across a network via many protocols, including HTTP.