ASP. NET provides three powerful list controls: DataGrid, DataList, and Repeater controls, but only the DataGrid control provides paging functionality. Relative datagrid,datalist and repeater controls have a higher style customization, so many times we prefer to use DataList or Repeater controls to display data.
The PagedDataSource class encapsulates the properties of the DataGrid control, which enables the DataGrid to perform paging.
Partial public properties of the PagedDataSource class:
AllowCustomPaging Gets or sets a value that indicates whether custom paging is enabled.
AllowPaging Gets or sets a value that indicates whether paging is enabled.
Count gets the number of items to be used from the data source.
CurrentPageIndex Gets or sets the index of the current page.
DataSource Gets or sets the data source.
Datasourcecount gets the number of items in the data source.
Firstindexinpage gets the first index in a page.
Iscustompagingenabled gets a value that indicates whether the custom paging is enabled.
Isfirstpage gets a value that indicates whether the current page is the first.
Islastpage gets a value that indicates whether the current page is the last page.
Ispagingenabled gets a value that indicates whether paging is enabled.
IsReadOnly gets a value that indicates whether the data source is read-only.
IsSynchronized gets a value that indicates whether access to the data source is synchronized (thread safe).
PageCount gets the total number of pages required to display all items in the data source.
PageSize Gets or sets the number of items to display on a single page.
Virtualcount Gets or sets the actual number of items in the data source when a custom paging is used.
The DataGrid control uses the PagedDataSource class to display data pagination, so DataList and Repeater can also use PagedDataSource to display pagination.
Private voidBinddata () {//DS Shim CodeDataView dv = ds. tables[0]. DefaultView; PagedDataSource Pds=NewPagedDataSource (); Pds.datasource=DV; Pds.allowpaging=true; Pds.pagesize=Ten; intTotalCount =Pds.pagecount; intCurrpage; //Here you can submit the page index in various waysCurrpage = request.querystring["Page"]; //Finally, then bind//both DataList and Repeater canDatalist1.datasource =Pds; Datalist1.databind ();}
1. Create a 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 object
DataTable tbl = ds. TABLE[0];
DataRow row = tbl. ROW[0];
Console.WriteLine (ros["OrderID"]);
②, checking data stored in a 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. Verifying data in a dataset
Properties of the ①, checksum DataColumn: Readonly,allowdbnull,maxlength,unique
Constrains collection of ②, DataTable objects: Uiqueconstraints,primarykey,foreignkeyconstraints
There is usually no need to deliberately 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 a DataTable object: 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 more than one dataset, you must use 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 the same counterpart, creating a new DataTable with the same structure as the original DataTable, but without any rows.
③, adding columns to 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 an expression-based column
Tbl. Columns.Add ("Itemtotal", typeof (Decimal), "Quantity*unitprice");
6. Modify the DataTable content
①, adding a 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);
②, modify the forward
Modify the contents of a row the corresponding content in the database is not automatically modified, and modifications 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 column's data is not modified
Obejct[] Acustomer ={null, "Newcompanyname", "Newcontactname", null}
DataRow Rowcustomer;
Rowcustomer = ds. tables["Customers"]. Rows.find ("ALFKI");
Rowcustomer.itemarray = Acustomer;
③, handling null values for 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;
④, deleting a 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 a 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]);
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 contents to an XML file, DatasetName is the root node name of the XML file.
DesignMode: Returns False if Dataset,designmode in the component is used at design time to return true.
HasErrors: Indicates whether the DataRow object in the dataset contains an error. If you commit a batch of changes to the database and set the ContinueUpdateOnError property of the DataAdapter object to True, you must check the dataset's HasErrors property to determine if there is an update failure after committing the change.
namespace and prefix: Specifying XML namespaces and prefixes
Relations: Returns a DataRelationCollection object.
Tables: Checks the existing DataTable object. Accessing the DataTable by index has better performance.
②, methods
AcceptChanges and RejectChanges: accepts or discards all pending changes in the dataset. When AcceptChanges is called, the RowState property of all rows with the RowState property value of added or modified will be set to unchanged. Any DataRow object marked as deleted will be removed from the dataset. When RejectChanges is called, any DataRow object marked as added will be removed from the dataset, and the other modified Datrow objects 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: Using the Copy method creates a new dataset with the same structure and the same row 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 all pending changes in the original dataset.
Getxml and GetXmlSchema: Use the Getxml method to get the string from the contents of the dataset and her schema information into XML format. If you only want to return schema information, you can use GetXmlSchema.
Haschange: Indicates whether the dataset contains a DataRow object that has pending changes.
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 a file, TextReader, data flow, or XmlReader.
Reset: Returns the DataSet to an uninitialized state. If you want to discard an existing dataset and start working on a new dataset, it is better to use the Reset method than to create a new instance of the DataSet.
③, Events
MergeFailed: Triggered when an exception occurs in the merge method of the DataSet.
2. DataTable
①, properties
②, methods
③, Events
ColumnChanged: Triggered after the contents of the column have been changed
Columnchangding: Triggers before the contents of a column are changed
Rowchanged,rowchanging,rowdeleted,rowdeleting.
3, DataColumn
①, properties
4. DataRow
①, properties
Haserror: Determines whether the row contains an error.
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 columns in the row.
RowError: Returns a string containing the row error information.
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 the Delete method of a DataRow object is called, ADO marks the row as deleted, and then calls the Update method of the SqlDataAdapter object to remove its Corresponding rows in the library.
If you want to completely delete a DataRow, you can call the Delete method, then call its Acceptechanges method, and you can use the Remove method of the DataRowCollection object to accomplish the same task.
3 How to traverse a dataset
foreach (DataTable dt in dataset.tables)
foreach (DataRow dr in Dt. Rows)
foreach (DataColumn dc in Dr. Table.columns)
Console.WriteLine (DR[DC]);
Talking about the usage of dataset
The dataset is developed for easy data processing by the ADO developers, is a collection of data, is designed to solve DataReader defects, DataReader data processing speed, but it is read-only, and once moved to the next line, you can not view the previous row of data, The DataSet is free to move the pointer. The data for the dataset is disconnected from the database. Datasets can also be used in multi-tier applications where the business object needs to pass the offline data structure to the client application if the application is running in a middle-tier business object to access the database.
Functions of the DataSet: Browse, Sort, search, filter, process hierarchical data, cache changes, and more. It can also be interchanged with XML data. The dataset can include multiple DataTable, which can be stored in a dataset for ease of operation, while the DataTable includes multiple DataRow, DataColumn, which can be viewed by these DataRow, DataColumn , manipulate the data in it, and return the result of the operation to the database, you can call the DataAdapter Update method.
Operation of the dataset:
DataSet ds=new DataSet ();
DataTable dt=new DataTable ("NewTable");
Ds. Tables.add (DT);
DataSet ds=new DataSet ();
DataTable Dt=ds. Tables.add ("newtable");
Both of these methods can add a DataTable to the dataset to choose from. After you add a DataTable, you add rows and columns to it.
DataSet ds=new DataSet ();
DataTable Dt=ds. Tables.add ("Newtables");
DataColumn Col=dt. Columns.Add ("NewColumn", typeof (int));
Col. Allowdbnull=false;
Col. maxlength=4;
Col. Unique=true;
The preceding code adds a column named "NewColumn" to the DataTable in the dataset with the type int and NOT NULL, with a maximum length of 4 and a true uniqueness.
Dt. Primarykey=new Datacolumn[]{dt. columns["ID"}
This code continues with the above code, adding a primary key column to a DataTable, which is a data group, and if there are multiple primary keys, simply add a column to the array. As follows:
Dt. Primarykey=new Datacolumns[]{dt. columns["OrderID"],dt. columns["ProductID"]}
To add a foreign key:
ForeignKeyConstraint FK;
Fk=new ForeignKeyConstraint (ds. tables["Customers"]. columns["CustomerID"],ds. tables["Orders"]. columns["CustomerID"]);
Ds. tables["Orders"]. Constraints.add (FK);
If the above code has created a primary key for the Cusomers table and orders,
This sentence adds a foreign key constraint.
The above is to create a constraint based on the CustomerID of the Customers table and the Orders table.
The following describes modifying the contents of a DataRow:
DataRow Dr=ds. tables["Customer"]. Rows.find ("ANTON");
if (dr==null)
Else
{
Dr. BeginEdit ();
dr["CompanyName"]= "newvalue";
dr["ContactName"]= "newValue2";
Dr. EndEdit ();
}
The above code locates the rows in the DataTable through the Find method of the row collection, finds the "ANTON" row, and modifies the values of the CompanyName column and ContactName column in the ANTON row. You can also call CancelEdit to cancel the modification by BeginEdit and EndEdit to cache the modification of the row.
Determine if a column is a null value:
DataRow Dr=ds. tables["Customers"]. Rows.find ("AAA");
if (Dr. IsNull ("ContactName");
..
Else
dr["ContactName"]=dbnull.value
This is to determine if the ContactName column is empty, and if it is not the null value, ah, it is very unreasonable, here only to demonstrate the practice of assigning null values to the column.
Delete DataRow:
There are two ways to remove the Datarow,delete method and the Remove method and the RemoveAt method. The difference is that the Delete method does not actually delete a row from the DataTable, but instead flags it as a delete, just a token, and the Remove method is a real delete from the DataRow, and the RemoveAt method is the index of the underlying row to delete. Column:
DataRow Dr=ds. tables["Table"]. Rows.find ("a");
Ds. tables["Table"]. Remove (DR);
Or
Ds. tables["Table"]. Remove (index);
The DR is the line where "a" is located, and it is deleted after being detected, and index is the number of "a". For its usage in the dataset, refer to the MSDN
DataRow Dr=ds. tables["Customers"]. Rows.find ("AAA");
if (Dr. IsNull ("ContactName");
..
Else
dr["ContactName"]=dbnull.value
This is to determine if the ContactName column is empty, and if it is not the null value, ah, it is very unreasonable, here only to demonstrate the practice of assigning null values to the column.
using system.data;
using system;
using system.windows.forms;
class datat{
static DataTable dt;//= new DataTable ();
Static DataSet ds;
static void Method1 () {
dt = new Da Tatable ("Name");
ds = new DataSet ();
dt. Columns.Add (New DataColumn ("ID", typeof (Int32)));
dt. Columns.Add (New DataColumn ("Name", typeof (String)));
dt. Columns.Add (New DataColumn ("Sex", typeof (String)));
dt. Columns.Add (New DataColumn ("Addr", typeof (String))),
}
static void Add (int id,string name,string Sex,string addr) {
DataRow dr = dt. NewRow ();
dr["id"] = id;
dr["Name"] = name;
dr["Sex"] = sex;
dr["Addr"] = Addr;
Dt. Rows.Add (DR);
}
static void Main () {
Datat DT = new Datat ();
Method1 ();
Add (+, "Join", "Male", "Beijing");
Add (101, "Lily", "FeMale", "Beijing");
Add (102, "JIM", "Male", "Beijing");
Ds. Tables.add (DT);
foreach (DataRow dr in Dt. Rows) {
MessageBox.Show (dr["ID"). ToString () + "" + dr["Name"]. ToString () + "" + dr["Sex". ToString () + "" +
dr["Addr"]. ToString (), "Message");
Console.WriteLine (dr["ID"). ToString () + "" + dr["Name"]. ToString () + "" + dr["Sex". ToString () + "" +
dr["Addr"]. ToString ());
}
try{
foreach (DataTable dt2 in DS. Tables)
foreach (DataRow Dr in DT2. Rows)
Console.WriteLine (dr["ID"). ToString () + "" + dr["Name"]. ToString () + "" + dr["Sex". ToString () + "" +
dr["Addr"]. ToString ());
}catch (Exception ex) {
Console.WriteLine ("DKFJKSDJFK");
}
}
}
About PagedDataSource paging properties with datasets and DataTable