Simplified and Extended Data Binding Syntax in Asp.Net 2.0 (Part1)

xiaoxiao2021-03-06  103

Introduction

The server-side data binding techniques that were introduced in ASP.NET version 1.0 revolutionized the way developers build pages that access data. No longer was there a requirement for complex and lengthy code sections that build up HTML tables or lists of values. However, Using ASP.NET 1.x, You Still Have to Write Code To Perform The Data Access and Expose The Data To The List or Grid Controls for Data Binding.

In version 2.0, new data source controls can be used to remove the need for any code at all, while still providing a whole range of features for extracting data that can be filtered, sorted and paged for display. They also support automatic updates to data For the New GridView, DetailsView and Formview Controls, Making It Extreme Easy to Build Data Access Pages with little or no server-side code being request.

To support these features, there have been both simplifications and extensions to the syntax used for data binding. The syntax used in version 1.x can be confusing, cumbersome, and is tedious and to write. In version 2.0, data binding statements are more concise, easier to use, and reduce complexity (of course, the existing version 1.x syntax is still supported). Plus, for hyperlinks in the new GridView control, you can now specify more than one column or expression for binding to the control ALOWING More Than One Value To BE Used When Constructioning The URL (HREF) Attribute of The Resulting HyperLink.

And, more than this, there are three new types of data binding statement you can use. OK, it may seem that this makes nonsense of the simplifications just described, but in fact these additions provide broader opportunities for data binding. There are two new expressions aimed at supporting XML data with the new data source controls added to version 2.0 of ASP.NET. There is also a new expression to provide two-way data binding in controls that support no-code automatic updating of the source data.This article Looks at:

THE SIMPLification of, And Extensions to Xml Data In Asp.Net 2.0

The Simplified Data Binding Syntax in ASP.NET 2.0

Many developers have questioned the verbose and seemingly inflexible nature of the statements that are required to perform data binding to ASP.NET list controls such as the Repeater, DataList and DataGrid. Plus, when writing pages in C #, it's not unknown for data type conversion Issues to arise, Because C # does Not Perform The Same Level of Implicit Data Type Conversion As Visual Basic .NET.

The EXISTING DATA BINDING SYNTAX IN ASP.NET 1.X

In ITS Simplest Form, The Format for Data Binding in ASP.NET 1.x IS:

<% # Container.dataitem ("expression")%>

In a list control, expression is usually the column name. For example, this code inserts the value from the CustomerName column in the current row into a Label control (notice the use of single quotes to enclose the data binding statement, which itself contains double Quotes:

Text = '<% # Container.DataItem ( "CustomerName")%>' However, any valid expression that returns a value can be used in a data binding statement. And the same syntax can, of course, be used outside list controls. For example, it can be used to display a value directly in the page, or as the value of an attribute for any. Other Server.

The limitation with this simple syntax is that values ​​can not be formatted. Instead, you must use the Eval method of the object that is exposing the data, referenced through the static DataBinder object. This method has two overloads, one of which takes an additional parameter That specifies the formatting to be applied to the value:

<% # DataBinder.eval (Container.DataItem, "Expression" [, "Format"])%>

THE FORMAT Parameter Is A String Value, Using The Value PlaceHolder Replacement Syntax (Called

Composite formatting) Like His:

Text = '<% # DataBinder.eval (Container.DataItem, "ORDERDATE", _

"{0: DDDD D mmmm"])%> '

The placeholder is always zero in ASP.NET 1.x, and the format string following the colon can be one of the predefined characters (such as C for currency, or t for the short version of the time), or a custom format string .

Notice the underscore at the end of the second line in the previous code listing. The data binding statement is code that is executed to produce the value that is displayed, and so when writing pages using Visual Basic .NET you must include the line continuation character if you break the code over more than one line. It is not required if you are writing the page in C #, or any language that does not depend on carriage returns to signify the end of a code line.For details of the characters and syntax used in formatting strings, see: http: //msdn.microsoft.com/library/en-us/cpguide/html/cpconformattingoverview.asp For details of the composite formatting syntax, see: http: //msdn.microsoft.com/ Library / En-US / CPGUIDE / HTML / CPCONCompositiveMatting.asp

Data Binding Statements in ASP.NET 2.0

One of the reasons that the two different approaches to the data binding syntax were originally made available is that using the Container object is more efficient at runtime than the Eval method of the DataBinder object. This is because the Eval method uses late-bound reflection to DETERMINE The Value Type. However, This Difference is Marginal in Almost All Cases.

In ASP.NET 2.0, you should generally use the Eval method. And, to make this easier, the DataBinder object that exposes it has been made the default context for all non-hierarchical (rows and columns) data binding expressions. This means that You can use a much simpler syntax. if you just want to display a value without formatting it, use the eval method Directly:

<% # Eval ("expression")%>

OR, IF you need to format the value, use the second overload That Accepts a format string:

<% # Eval ("expression" [, "format"])%>

The Format Parameter Works Here Just Like It Does In v1.x. so, for example, you can format the value in a column named price as currency using: <% # eval ("price", "{0: C}") %>

And, AS in v1.x, you can use more completion strings to display text as well as the current row value:

<% # Eval ("Price", "Special Offer {0: C} for Today!")%>

USING MULTIPLE DATA Bound Values ​​in a HyperLink Control

Another area where ASP.NET 2.0 extends the data binding syntax of v1.x is when you use a HyperLinkField in the new GridView or DetailsView controls. We do have room to not cover these controls in detail here, though any developer who has to display hierarchical data will no doubt have already headed straight for these great new controls and experimented with their capabilities. They can be used in conjunction with the new data source controls to provide "no-code required" display of data from almost any data source. For example, this is all you need to display the contents of the products Table in Sample Northwind Database In SQL Server:

Connectionstring = "Server = localhost; database = northwind; uid = x; pwd = y"

SelectCommand = "SELECT ProductID, ProductName, QuantityPerunit,

Unitprice, UnitsInstock, Discontinued from Products

/>

The Screenshot Below Shows The Results. This Example, Basic-Binding.aspx, Is Included in The Samples You Can Download for this Article from

http://www.daveandal.net/articles/databinding-syntax/.figure 1

However, the new data binding capability comes to light once you turn off automatic column generation by adding the attribute AutoGenerateColumns = "False" to the declaration of a GridView control, or AutoGenerateRows = "False" to the declaration of a DetailsView control. You can ........................ ..

The DataNavigateURLFIELDS PROPERTY

The new HyperLinkField control exposes a property named DataNavigateUrlFields, which is broadly equivalent to the DataNavigateUrlField property of the HyperLinkColumn you would use in a DataGrid control in v1.x. But, as the name suggests, it accepts more than one column name or expression. In The Control Declaration, You Specify The Column Names as a comma-Delimited List, for example:

DataNavigateURLFIELDS = "ProductID, SupplierId, ProductType"

There is also a DataNavigateUrlFormatString property exposed by the HyperLinkField control - just like the HyperLinkColumn control in version 1.x. The useful feature with the HyperLinkField control is that you can now take advantage of ability of the DataNavigateUrlFields property to bind to multiple columns, and Insert More Than One Value from The Current Row Into The NavigateURL (The Href Attribute) of The Resulting Hyperlink.

AS An Example, The Code Below Uses Feature To Provide a Hyperlink That Contains Two Values, Both Extracted from The Current Row of The Customers Table, for The Href Attribute:

SelectCommand = "Select Customerid, CompanyName, City from Customers" />

AutogenerateColumn = "false">

DataTextField = "Customername"

DataNavigateURLFIELDS = "Customerid, City"

DataNaviGateURLFORMATSTRING =

"http://yoursite.com/showcustomer.aspx?id={0 }&city={1}" />

The resulting value for the href attribute will be something like this:

"http://yoursite.com/showcustomer.aspx?id=alfki&city=berlin"

The Screenshot Below Shows The Results. This Example, HyperlinkField.aspx, IS include in the samples you can nownload for this article from

http://www.daveandal.net/articles/databinding-syntax/.

Figure 2

Setting the datanavigatearcharchfields property at runtime

You can also set the DataNavigateUrlFields and DataNavigateUrlFormatString properties at runtime using code To set the DataNavigateUrlFields property you must create a String array and assign it to the DataNavigateUrlFields property during the Load event of the parent GridView or DetailsView control.:

'Event Handler Specified in The Onload Attribute of The Control

Sub GridView1_Load (Byval e AS Object, Byval E as Eventargs)

'Create and Populate the array of column names

DIM AFIELDS (1) AS STRING

Afields (0) = "CUSTOMERID"

Afields (1) = "city"

'get reference to the column as a hyperlinkfield control instance

'specify the index of the color ohlfield as hyperlinkfield = ctype (Sender.columns (1), HyperLinkField

'set the datanavigatearcharchfields protety

Ohlfield.datanavigateURLFIELDS = Afields

Ohlfield.datanavigateURLFORMATSTRING = _

"http://yoursite.com/showcustomer.aspx?id={ }&city={1}"

End Sub

The code above is in Visual Basic .NET. The equivalent in C # is shown below. Notice that the control name (GridView1) is referenced directly, because the sender parameter is of type Object and can not be implicitly converted to a GridView type (and, Hence, Does Not Have A Column Collection:

Void GridView1_Load (Object Sender, Eventargs E) {

String [] Afields = New String [2];

Afields [0] = "CUSTOMERID";

Afields [1] = "city";

HyperlinkField Ohlfield = (HyperLinkField) GridView1.columns [1];

Ohlfield.datanavigateURLFIELDS = Afields;

Ohlfield.datanavigateURLFORMATSTRING =

"http://yoursite.com/showcustomer.aspx?id={ }&city={1}"

}

The New Two-Way Data Binding Syntax

When building pages that use list or grid controls in ASP.NET 2.0, the new data source controls make it much easier than the v1.x approach of using code in the page to generate a DataReader or DataSet instance, and then binding this to the control. in version 2.0, you simply place a data source control on the page, and link it to the list or grid control using the DataSourceID attribute of property of the control. you saw an example of this in the earlier section "Using Multiple Data Bound Values ​​in a HyperLink Control.

This approach can be used with any of the list controls that are provided with ASP.NET 2.0, including those that were originally introduced in version 1.0 (for example, the DataGrid, DataList, Repeater, ListBox, and HtmlSelect controls). However, data Source Controls Really Come Into the New GridView, DetailsView and Formview Controls.automatic Updates with the New Data Source Controls

The original version's (1.0) list and grid controls are effectively "read-only", in that you have to write code that is executed in response to events raised by controls within the list or grid (for example, when the user clicks an Update or Delete link) This code must collect the values ​​in the relevant row and then execute some code you've written to push these values ​​back into the data store -.. possibly using stored procedures or explicit SQL statements in other words, data binding is Only Being Used to Populate The List or Grid Control.

In the GridView, DetailsView and FormView controls, this is no longer the case. As long as the data source is updateable, and you have provided the appropriate update, insert and delete commands, the control will automatically push changes to the values ​​in the list or grid control to which it's attached back into the data source. you can specify the update, insert and delete commands as explicit SQL statements or use stored procedures if you need to interact with a more complex database table structure.

What's important with respect to the topic of this article, however, is how these new controls affect the syntax used for data binding. When the columns or rows for a GridView or DetailsView control are auto-generated, or specified using a the pre-defined field types such as BoundField, HyperLinkField, or CheckBoxField, the data source control can figure out what to do when it's time to push changes back into the data store by looking at which columns each of the field types is bound to.But, if you use a TemplateField in a GridView or a DetailsView, you must declare all the content for that column or row yourself, just as you would when using a TemplateColumn in a DataGrid control. And, if you use a FormView control, you always have to declare All the content yourself. Like The V1.0 Repeater Control, The Formview Control Does Not Support Pre-Defined Column Types - IT Uses Only Templates for Content Generation.

Inside the templates of a TemplateField, or in the templates of a FormView control, you use data binding statements to connect the controls you declare there with the columns in the data source control. The interesting point is that the data binding technology must, in this Case, Support Both "Read" and "Write" Operations, Rather Than Being "Read-Only" AS HAS ALWAYS BEEN THE CASE DATA BINDIND, AND IS Supported THROUGH A New Method Called Bind.

The Bind Method

As With The Eval Method, The Bind Method Has Two overloads, Which Means That It Can Be Used with or without the "format" parameter:

<% # Bind ("expression" [, "format"])%>

In Fact, Other Than Specifying the New Method Name, The Bind Method. To Bind An Attribute of a Control To The CompanyName Column, You Use: <% # Bind ("CompanyName")%>

If you want to bind an attribute of a control to a value That Requires Formatting, You Add The Format Parameter:

<% # Bind ("ORDERDATE", "{0: DDDD D mmmm})%>

To demonstrate the Bind method, the following code shows a SqlDataSource control with parameterized SQL statements specified for the UpdateCommand and InsertCommand property attributes. The data source control exposes a two-column rowset containing the ID and name of products from the SQL Server Northwind sample database :

SelectCommand = "SELECT ProductId, ProductName from Products"

UpdateCommand = "Update Products Set ProductName = @ Productname

Where produter = @ ProductID

INSERTCOMMAND = "Insert INTO Products (ProductName)

VALUES (@ProductName) "

/>

The next listing shows how the templates of a FormView control can be declared to allow the product name to be edited or a new product to be added. For this to work, the FormView control must know which is the primary key column in the source data , and this is declared using the DataKeyNames attribute (multiple column primary keys are specified using a comma-delimited list of column names in the control declaration, or a String array of column names at runtime).

Datakeynames = "ProductID" allowpaging = "true">

<% # eval ("productname")%>

CommandName = "edit" text = "edit details" />

CommandName = "new" text = "add new product" />

Text = '<% # bind ("ProductID")%>' />

Text = '<% # bind ("productname")%>' />

Text = "Update" runat = "server" />

Text = "Cancel" runat = "server" />

Text = '<% # bind ("productname")%>' />

Text = "add" runat = "server" />

Text = "Cancel" runat = "server" />

Then each template section declares a control to either display or allow editing of the product name. In the ItemTemplate, where the value is just being displayed, the code can use the Eval method to bind to the ProductName column. In the EditItemTemplate and the InsertItemTemplate , the product name is displayed in a TextBox control, allowing it to be edited or entered. Because we want to push these values ​​back into the database, the Bind method must be used here.One important point to note is that the ProductID column is . the primary key in the table, and so it is "read-only" and can not be changed in the EditItemTemplate However, it is required to populate the @ProductID parameter of the SQL UPDATE statement - which means it must be placed in an ASP .NET server control (in this case a Label) and bound to the source rowset using the Bind method. If the Eval method is used here, the control will not be able to populate the @ProductID parameter in the SQL statement.

The ProductID is not required in the InsertItemTemplate, because this is an IDENTITY column in the database - and so it will be populated automatically when a new row is added For this reason, the SQL INSERT statement has no parameter for the ProductID; hence,. there is no requirement to display the value in a server control within this template, or use the Bind method. The only value that is required is the new product name, and the Bind method used with the TextBox where this is entered will push the new Value Into The Database Table.

The Screenshot Below Shows The Results. This Example, Bind-method.aspx, IS INCLUDEDITHOASOM http://www.daveandal.net/articles/databinding-syntax/.

Figure 3

To cause an update, delete or insert operation to take place in a FormView control, you must provide the relevant links or buttons to initiate the process yourself. However, as long as you use the appropriate values ​​for the CommandName property attributes ( "Edit" , "New", "Update", "INSERT", "Delete" or "cancel") The control will automaticly Wire the Up to Write Any Code. For more details of the form for more details of the Formview Control See The System.Web.ui.WebControls Namespace in The Reference Section of the SDK Installed with the .net framework, or available online from http://msdn.microsoft.com.when to use the Bind Method

WHEN You Use Templates in A GridView, DetailsView or Formview Control, you Should Be Aware of a Few Points:

The Bind method is responsible for providing the values ​​for the parameters declared in the SQL statements that push changes to the data back into the database. Therefore, all the controls that provide values ​​for the parameters in the SQL statement for the current operation must use the Bind method. in the earlier example, the control for the ProductID in the EditItemTemplate is a Label that does not allow the value to be edited (it is the primary key for the row). However, the value is required to populate the @ ProductID Parameter In The SQL Update Statement, Ando The Bind Method IS Used, Rather Than The Eval Method. However, Because ProductId IS An Identity Column Withnin The Database, A Value ISN '

转载请注明原文地址:https://www.9cbs.com/read-123983.html

New Post(0)