Data Binding in ASP. NET 2.0

Source: Internet
Author: User
Tags microsoft access database
The first version of ASP. NET has created a set of new database binding controls. With the support of these controls, data visualization and editing are much simpler. One of the most important controls is the DataGrid Control. However, this control also has many disadvantages. It provides some built-in functions for data sorting, paging, and editing, but must be implemented manually.

The new version of ASP. NET 2.0 adopts a new method to solve many problems of previous versions and provides standard functions. Now you can sort and edit any data source by page-in most cases, no code is required. Since almost all dynamic web programs need to take into account the interaction with the database, fortunately in ASP. NET 2.0, we can easily implement the following operations:

· Select the data we need in the database and display it on the page.

· Use the gridview control to implement sorting, paging, and data caching functions, which makes the data we get more intuitive and orderly.

· Update, insert, and delete data are frequently encountered in daily development. The gridview control makes all of this more efficient and simple.

· When the data volume is large, you need to consider data filtering to quickly find the required data. In the following sections, I will introduce in detail any data filtering function.

Since this article mainly discusses the knowledge of data access, we will first introduce the new functions of ASP. NET 2.0 in this regard:

· Data Source Control-Asp. NET 2.0 introduces declarative data source controls that expose data from backend storage (such as SQL databases, intermediate layer business objects, or XML files) to data binding controls on the page. The data source control also provides functions such as sorting, paging, caching, updating, inserting, and deleting data. The data binding control can automatically call these functions without writing any code.

· New data binding controls-except for retaining ASP. except some data binding controls in net 1.x, Asp. NET 2.0 also includes new data binding controls such as gridview, detailsview, formview, Treeview, and menu. We can customize these controls to display data in different ways. The gridview, detailsview, and formview controls can also automatically call the data source function, making it easier to add sorting, paging, and update operations to the data driver page.

· Data Control parameters-the data source can use the data control parameter objects in ASP. NET 2.0 to accept input parameters from various sources. Using these parameter objects, you can easily provide server control property values, sessions, applications, Cookie and querystring fields, and user configuration file attributes to parameterized data operations. With these parameters, you only need a small amount of custom code or no need to customize code to support filtering and master/detail schemes.

· Improved data binding syntax-Asp. in NET 2.0, databinder. the eval Data Binding syntax has been simplified, and we can also associate two-way data binding with control properties to allow automatic passing of values to the data source for update, insert, or delete operations. For Hierarchical XML data, ASP. NET 2.0 also contains an XPATH-based Data Binding syntax.

· Use the SQL express local file database-to simplify development, Asp. NET 2.0 now supports the ability to connect to the SQL express database as a local file in an application, eliminating the need to provide the database to the server for development purposes only. Of course, you can still connect to the server-based SQL database.

ASP. NET 2.0 has added two new server controls to implement the data binding model. These two new server controls can process many complex data solutions, which makes it unnecessary for developers to understand a series of Operating Mechanisms in the data binding process, in this way, we can focus on the framework and performance improvement of the program, rather than the repeated code writing process.

To fully understand the data binding model, we will introduce the two new server controls:

  Data Source Control

The data source control does not have a specific representation, but represents a specific back-end data storage, such as a database, business object, XML file, or XML Web Services. The data source control also supports a variety of data functions (such as sorting, paging, filtering, updating, deleting, and inserting), and the data binding UI control can automatically use these functions. Other advantages of the data source control include the automatic data binding function, which eliminates the need to call the databind () method, thus greatly reducing the amount of code required. It has more extension support during design and retains the flexibility of the 1.x version.

The existing data source control in ASP. NET 2.0 is as follows:

Name Description
Sqldatasource Access SQL Server, OLE DB, ODBC, Oracle, and other database systems with custom. NET data provider (the provider can be MySQL or Firebird ).
Objectdatasource Supports binding to intermediate layer objects, such as data access layer or service components.
Accessdatasource You can easily operate the Microsoft Access database by specifying the file name.
Sitemapdatasource Supports binding to a level exposed by the ASP. NET 2.0 site navigation provider.
Xmldatasource Supports binding to XML files or documents.

  Data Binding Control

The data binding control is a UI control that marks the data as the client device or browser that sends the request. The data binding control can automatically bind data exposed from the data source and obtain data at the appropriate time in the lifecycle of the page request. These controls can also choose to use data source functions, such as sorting, paging, filtering, updating, deleting, and inserting. The data binding control connects to the data source control through its performanceid attribute. You may be familiar with some data binding controls in ASP. NET 1.x, such as DataGrid, datalist, repeater, and list controls such as dropdownlist. ASP. NET 2.0 also contains several new data binding controls, such:

Name Description
Gridview Displays data in a grid format. This control is an evolutionary form of the DataGrid Control and can automatically use the data source function.
Detailsview A single data item is displayed in a tag/value pair table, similar to the form view in Microsoft Access. This control can also automatically use the data source function.
Formview A single data item is displayed once in a form defined by a custom template. Displays a single data item in a tag/value pair table, similar to Microsoft? The form view in access. This control can also automatically use the data source function.
Treeview Data is displayed in the layered tree view of a scalable node.
Menu Displays data in a hierarchical dynamic menu (including a pop-up menu.

  Data Binding in ASP. NET 2.0

In web programs, one of the most common functions is to display data from SQL databases such as Microsoft SQL Server and Oracle or other oledb or ODBC data storage areas. The sqldatasource control can represent a direct connection to the database in a web application, and the data binding control can be used to automatically retrieve data. In the past, we had to write a lot of code for database connection and command query. Now the sqldatasource control encapsulates the ADO. Net code that implements these functions. Because data query is directly specified as the property of the data source control, because data query is still maintained in the page code, we call it a two-layer model. For this reason, the sqldatasource control is usually intended for small amateurs or personal sites that do not require fully encapsulated data intermediate layer objects. Later in this tutorial, we will discuss the objectdatasource control, which is encapsulated for large enterprises in the middle layer that require database queries.

To demonstrate how to bind data in a database, the example in this section uses a new data binding control named gridview. The gridview control is a new data binding control that uses a grid to present data in ASP. NET 2.0. Each row in the grid corresponds to a data record, and the column represents the record field. The gridview control is the official successor of the popular control DataGrid in ASP. NET 1.x. The 2.0 version still supports DataGrid because of its compatibility, but it is no longer displayed in the toolbox. Therefore, do not use it in a new project. If the new control gridview not only provides all the functions of the old control, but also outlines more comprehensive new functions, why should we use the old control? In particular, the gridview can work better with the new data source provider concept.

The main functions of the gridview control are as follows:

· Data source controls bound to any plane or multi-layer structure (only the first layer.

· Built-in sorting function.

· Select data records.

· Update and delete data records.

· Multiple key fields are supported.

· Multiple fields can be used to create hyperlinks.

· Built-in paging function.

· Programmatic access to the gridview object model to dynamically set attributes and handle events.

· New column types such as checkboxfield and imagefield.

· Visual adjustment based on theme and style.

· Adjust the display result based on different (mobile) devices.

· Specify the background image.

Create a read-only report and its working principles:

The simplest data driver page is to display a read-only report, which mainly displays some data in the database. It does not allow users to operate on their representations and modify the data. If you want to create a read-only report in the SQL Server database, you must first configure a sqldatasource data source on the page, then, specify the "performanceid" attribute of a data binding control as the "ID" attribute of the sqldatasource data source control. In this way, a connection is established between the data source control and the data binding control.

In the following example, the gridview control is bound to a sqldatasource control connected to the SQL Server database.

Step 1: create an "ASP. NET web site" project named "gridviewsqldatasource"

Step 2: drag a "gridview" control to the page and click "Smart Tag" in the upper right corner ". Select "new data source" from "Select data source". The following window is displayed:

Step 3: Select "Database" as the data source type of the program in the data source Configuration Wizard. The default "ID" is sqlperformance1. After you click "OK", the following window appears:

Step 4: click "New Connection" in the window above to display the "database connection" window, because we want to display information in the SQL Server 2000 "pubs" database in the gridview, we choose "pubs" database as the source for data reading. The following figure shows the selected image:

Step 5: confirm the selected database and click "OK". VS 2005 will automatically set your connection string. In this example, "Data Source = hoowoo; initial catalog = pubs; Integrated Security = true ". Click "Next" in the pop-up window. The following window is displayed:

Considering the security performance of the database, we hope to hide the information of database connection strings in other ways. Here, we create an alias for the connection string and save it in the web. config file. VS 2005 automatically maps aliases and connection strings to achieve database connection.

Step 6: click "Next". The following window appears:

 
You can directly specify a table, select some fields, and click "Next" to complete the database configuration process.
 
After the program is executed, the page is displayed as follows:

Now let's analyze the generated Page code. To view the code, right-click the page and select "view code.

<Form runat = "server">
<Asp: gridview id = "gridview1" performanceid = "sqlperformance1" runat = "server">
<Columns>
<Asp: boundfield headertext = "last name" datafield = "au_lname"/>
<Asp: boundfield headertext = "first name" datafield = "au_fname"/>
<Asp: boundfield headertext = "city" datafield = "city"/>
<Asp: boundfield headertext = "state" datafield = "state"/>
<Asp: boundfield headertext = "zip code" datafield = "Zip"/>
<Asp: checkboxfield headertext = "contract" datafield = "contract"/>
</Columns>
</ASP: gridview>
<Asp: sqldatasource id = "sqldatasource1" runat = "server"
Selectcommand = "select [au_lname], [au_fname], [City], [State], [Zip] from [authors]"
Connectionstring = "<% $ connectionstrings: pubs %>"/>
</Form>

In this example, the DataGrid Control specifies its "datasourceid" attribute as "sqldatasource1", so that the association between the data binding control and the data source control is established.

The gridview control reflects the data record fields returned by sqldatasource to dynamically generate grid columns. By adding a datacontrolfield object to the columns set of the gridview, you can also specify the explicit column field to be displayed. This allows you to specify the columns to be displayed and their relative sequence. Other field types that can be allocated to the columns set include imagefield, hyperlinkfield, commandfield, buttonfield, and templatefield. We can choose
Field type.

The connectionstring attribute of sqldatasource specifies the connection string to the database, and the selectcommand attribute specifies the query to be executed to retrieve data. The connection string can be specified by literal text on the page. However, in this example, this attribute uses a new syntax to query the actual value of the connection string in Web. config.

In this example, the code snippet in Web. config is as follows:

<Connectionstrings>
<Add name = "pubs" connectionstring = "Data Source = hoowoo; initial catalog = pubs;
Integrated Security = true "providername =" system. Data. sqlclient "/>
</Connectionstrings>

By adding a "<connectionstrings> </connectionstring>" node to Web. config, You can map the connection string to the alias "pubs" specified by the "name" attribute. Storing connection strings in Web. config is a recommended practice for any ASP. NET application. This not only enables centralized program management, but also protects database connection strings. In VS 2005, we can use a command line tool in ASP. NET 2.0 to encrypt this node for further security.

Note: The sqldatasource control is not limited to connecting to the SQL Server database. It can actually connect to any hosted ADO. net provider configured as system. Data. Common. dbproviderfactory. By default,. NET Framework machine. config contains four providers:

<Configuration>
<System. Data>
<Dbproviderfactories>
<Add name = "ODBC data provider" invariant = "system. Data. ODBC" type = "system. Data. ODBC. odbcfactory,..."/>
<Add name = "oledb data provider" invariant = "system. Data. oledb" type = "system. Data. oledb. oledbfactory,..."/>
<Add name = "oracleclient data provider" invariant = "system. Data. oracleclient" type = "system. Data. oracleclient. oracleclientfactory,..."/>
<Add name = "sqlclient data provider" invariant = "system. Data. sqlclient" type = "system. Data. sqlclient. sqlclientfactory,..."/>
</Dbproviderfactories>
</System. Data>
</Configuration>

The providername attribute of sqldatasource can be set to a fixed name of any valid provider Factory (default: system. Data. sqlclient ). Note: If you change the provider name, make sure that the connectionstring and selectcommand attributes use the correct syntax of the selected provider.
We can also specify a stored procedure to replace an SQL command for the selectcommand attribute of the sqldatasource data source control, and use the stored procedure with greater flexibility. To implement this function, you can set the selectcommandtype attribute of the sqldatasource data source control to "storedprocedure ".

Now we can use the "tenmostexpensiveproducts" Stored Procedure of the example database northwind provided by SQL Server to implement a read-only report.

This stored procedure selects "productname" and "unitprice" fields in the "Products" table. The Code is as follows:

Create procedure "Ten Most Expensive Products"
Set rowcount 10
Select products. productname as tenmostexpensiveproducts, products. unitprice
From Products
Order by products. unitprice DESC

The page code is as follows:

<Form ID = "form1" runat = "server">
<Asp: gridview id = "gridview1" performanceid = "sqlperformance1" autogeneratecolumns = "false"
Runat = "server">
<Columns>
<Asp: boundfield datafield = "tenmostexpensiveproducts" headertext = "product"/>
<Asp: boundfield datafield = "unitprice" dataformatstring = "{0: c}" headertext = "price"/>
</Columns>
</ASP: gridview>
<Asp: sqldatasource id = "sqldatasource1" runat = "server"
Selectcommand = "Ten Most expensiveproducts" connectionstring =
"<% $ Connectionstrings: northwind %>" selectcommandtype = "storedprocedure"/>
</Form>

In this example, we can set the selectcommandtype attribute of the sqldatasource data source control to "storedprocedure", for example:

You can also follow the steps below in the data source Configuration Wizard:

When you go to the "Configure SELECT statement" window, select "specify a custom SQL statement or stored procedure" and click "Next"

In the "Custom statement or stored procedure" window, select the "Stored Procedure" item. And select "Ten Most Expensive Products"

After a series of operations are completed, press F5 to execute the program. The page is displayed as follows:

Generally, the sqldatasource data source control only returns dataview from the DataSet object that contains the query results. You can configure the sqldatasource data source control to return data as a datareader. When you want to read-only and forward data access, datareader has better performance than dataset. However, when you need paging support for the sqldatasource data source control, you must use dataset.

Set the datasourcemode attribute of the sqldatasource data source control to "datareader". The default value is "dataset". For example:

The page code is as follows:

<Form ID = "form1" runat = "server">
<Asp: gridview id = "gridview1" performanceid = "sqlperformance1" autogeneratecolumns = "false"
Runat = "server">
<Columns>
<Asp: boundfield datafield = "tenmostexpensiveproducts" headertext = "product"/>
<Asp: boundfield datafield = "unitprice" dataformatstring = "{0: c}" headertext = "price"/>
</Columns>
</ASP: gridview>
<Asp: sqldatasource id = "sqldatasource1" runat = "server"
Connectionstring = "<% $ connectionstrings: northwind %>"
Selectcommand = "Ten Most Expensive Products"
Selectcommandtype = "storedprocedure"
Performancemode = "datareader"/>

Source: http://blog.csdn.net/hiyavip/archive/2005/12/31/566835.aspx

Related Article

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.