ASP. Network 2.0Data Binding
I,Target
1.ASP. NETData Binding standard controls
2.GridViewControls to bind data
-GridView formatted data output
-GirdView data paging and sorting
-GirdView show images
-GridView template Column
-Add, modify, and delete data in the GridView
II,ASP. NETData Binding in
Data Binding is to transfer data from the data source to the control.
Controls that support data binding all have the following features:
Has a property named DataSource
Has a method named DataBind
To bind a control, first initialize a data source and then use the DataBind method for the control.
Data Binding Process
1. Data Source
• ASP. NET 1.1 uses DataSet as the data source. To create a data source, you must use DataAdapter to connect to the database and use DataCommand to obtain the query results and store them in the data source.
• ASP. NET 2.0 provides drag-and-drop controls for database connection and data source configuration.
In most cases, we need to perform the following operations frequently on the database:
. Query some data from the database
. Obtain some input from the user and update it to the database.
. Find some records from the database and delete them.
Most of the code is very similar. We usually use paste copy to complete the process. However, this often leads to a problem: we forget to modify the name of a data table or column, or determine whether the data table is empty. To avoid such errors, using an encapsulated database connection object should be a good solution.
• The main data source objects include the following three
Used to access the XML document xmldatasource
This interface is used to access class data source objects compiled by programmers. Objectdatasource
Used to access all database objects that support SQL statements, such as sqlserver. Oracle, access, and sqldatasource.
2. Supports standard controls for Data Binding
• Dropdownlist
• ListBox
• Checkboxlist
• Radiobuttonlist
• Bulletedlist
III,GridViewWidget
• In ASP. NET 1.0 era, the DataGrid Control is widely used to display the database content control, you only need to drag and drop the DataGrid Control to the page, set a small number of properties, you can display data, and sort the data. You can even edit the data.
• Even so, the DataGrid still has its limitations.
• Although the cyclird control has so many attributes, some of its functions, such as data sorting, record paging, modification or deletion, still need to write some code, in addition, these codes are highly prone to errors.
1.DataSource:
• The datasource control is used to extract data from the database and display the content of the datasource control. We can use the gridview control. An important attribute of this control is datasource ID. By specifying this attribute, let's determine the content of the datasource control displayed by the gridview control.
SQL source connection example
2. format the output
• After displaying the data, we also want the data to be output in a certain format.
• The gridview control provides the attributes used to adjust the display output mode. If you are a talented person, you can modify the back color, Font, fore color and other attributes to modify the display mode, or through head sytle, row
Style, alternatingrowstyle, and footsytle attributes to modify the cell format. If you are not as beautiful as you are
It does not matter. You can use the auto format attribute to set the display mode to format the output.
• You can also use the edit columns attribute to add or delete display elements, or modify the display mode of the display elements. Format output
• In the element output mode attribute, you can use the formatstring attribute to set the Display Mode Based on the Data Type of the display element. The setting method is {0: c}, and C indicates that the amount is displayed.
• Use skin to format the output
• When a Data Binding event occurs, you can handle it as required to display special output results.
Demo
• Standard auto format
• Use skin
• Formatted output according to user requirements (for example, highlighting items with zero inventory)
3. DisplayMaster/detailData
• There is often a one-to-many data relationship in the database. Therefore, you often need to display multiple data records based on a condition. At this time, the GridView control can be combined with the selection control to conveniently complete the task.
• The GridView control can be bound to the selected control by setting properties.
Demo
• The GridView is bound to the DropDownList.
4. Paging and sorting
• When the displayed data volume is too large, one page may not be displayed. In this case, we need to use a technology. Divides large data into several data pages, and each page displays only a certain amount of data. This technology is called Paging
• When viewing data, you may want to sort the data display by column values, such as displaying exam scores from high to low or displaying prices from low to high. So sorting technology is also very important in data display.
• Paging and sorting can also be implemented in javasird of ASP. NET 1.x, but some code is required. In the GridView, You can conveniently implement paging and Sorting Technology without writing any line of code.
• Pagination can be configured by setting the Enable Paging attribute and the paging attribute in the attribute.
• You can set Sorting by using the sortexpression attribute in Enable Sorting and unit attributes.
• Paging Demo
• Sort Demo
• Paging and sorting Demo
5. display images
• You can easily display images in a column in the GridView.
• Add an ImageField attribute column and specify the Data Binding object for this attribute column to conveniently display images.
• Show image column examples
6. UseTemplateFields
• The GridView allows different types of cells, such as the BoundFileds and ImageFields we have demonstrated. We can also output HTML in cells or use controls at the ASP. NET Server end.
• For example, we want to judge the HireDate column in NorthWind. For employees whose dates exceed a certain number of days, we will display different contents.
• For the above requirements, we can write the following functions to complete this function.
String ComputeSeniorityLevel (TimeSpan ts)
{
Int numberOfDaysOnTheJob = ts. Days;
If (numberOfDaysOnTheJob> = 0 & numberOfDaysOnTheJob <= 1000)
Return "Newbie ";
Else if (numberOfDaysOnTheJob> 1000 & numberOfDaysOnTheJob <= 4000)
Return "Associate ";
Else if (numberofdaysonthejob> = 4000 & numberofdaysonthejob <= 8000)
Return "one of the regulars ";
Else
Return "An ol 'fogey ";
}
• At the same time, use <% # computesenioritylevel (datetime. Now-ctype (eval ("hiredate "),
Datetime) %> bind data
Use templatefields --- 2
• Templatefield can be used not only as the HTML output container, but also as an ASP. NET Server Controller
Container.
• For example, when displaying the content of a database, we need to display a one-to-many relationship.
Use the bulletedlist control to display multiple columns.
• Use the bulletedlist example in templatefields
DataView territoryData; // this DataView will hold all of the Territories, loaded at Page_Load
Protected void Page_Load (object sender, EventArgs e)
{
// Load all of the territories into a DataView from the SqlDataSource
TerritoryData = (DataView) territoriesDataSource. Select (DataSourceSelectArguments. Empty );
}
Void employeesGridView_RowDataBound (object sender, GridViewRowEventArgs e)
{
// For each DataRow in the GridView, programmatically access the BulletedList, filter
// The dataview Based on the gridview row's employeeid value and bind the filtered dataview
// To the bulletedlist
If (E. Row. rowtype = datacontrolrowtype. datarow)
{
Bulletedlist BL = (bulletedlist) E. Row. findcontrol ("bltterritories ");
Territorydata. rowfilter = "employeeid =" + (datarowview) E. Row. dataitem) ["employeeid"]. tostring ();
BL. datasource = territorydata;
BL. databind ();
}
}
7. display detailed data
• In a one-to-many table relationship, we want to display more information by clicking a record. Or there are too many columns in the table. We want to display some basic information and all the information of the selected columns. In this case, we need a drilling-down Association table.
• For example, the northwind database contains an order and an Order Details table, where order contains
Demo
• Display order and order details
• In the preceding example, if a data table is displayed on the left, the detailed table on the right does not change. This may seem a little uncomfortable. Pass
Void ordergridview_pageindexchanged (Object sender, eventargs E)
{
Ordergridview. selectedindex =-1;
}
• Track page changes as follows to solve the above problems.
Demo
• Use the pageindexchanged event
8. Sum page data
• As shown in the previous example, we may also calculate the data displayed on the page. For example, we want to sum the total price of all orders and display them at the bottom. • Using the databinder. Eval method, we can obtain the data in datarow and sum it.
Demo
• Page data summation example
Decimal priceTotal = 0;
Int quantityTotal = 0;
Void detailsGridView_RowDataBound (object sender, GridViewRowEventArgs e)
{
If (e. Row. RowType = DataControlRowType. DataRow)
{
// Add the UnitPrice and QuantityTotal to the running total variables
PriceTotal + = Convert. ToDecimal (DataBinder. Eval (e. Row. DataItem, "UnitPrice "));
QuantityTotal + = Convert. ToInt32 (DataBinder. Eval (e. Row. DataItem, "Quantity "));
}
Else if (E. Row. rowtype = datacontrolrowtype. footer)
{
E. Row. cells (0). Text = "totals :";
// For the footer, display the running totals
E. Row. cells (1). Text = pricetotal. tostring ("C ");
E. Row. cells (2). Text = quantitytotal. tostring ("D ");
E. Row. cells (1). horizontalalign = horizontalalign. Right;
E. Row. Cells (2). HorizontalAlign = HorizontalAlign. Right;
E. Row. Font. Bold = True;
}
}
9. How to edit and delete data
• Data Binding for editing and deleting operations can be completed by setting properties in SQL DataSource
How to edit and delete data
• The code for adding, modifying, and deleting data records is automatically generated after the first CheckBox in the Wizard is selected.
Once a data CheckBox is selected, make sure that the database is not changed after it is retrieved from the database.
.
• Once you want to edit or delete data through the GridView, a primary key must exist in the data column queried by the SQL DataSource.
• After configuring the data source, you only need to select Enable Update and Enable Deleting to edit and delete data.