ASP. NET 2.0: discard the DataGrid. There is a new grid control! [Msdn]

Source: Internet
Author: User
ASP. NET 2.0: discard the DataGrid. There is a new grid control! Release date: 2005-1-13 | Updated on: 2005-1-13

Dino esposito

See ASP. NET May 2004 technology preview in 2.0. All information contained in this document may be changed.

This article discusses:

ASP. NET 2.0 gridview, formview, and detailsview

Differences Between DataGrid and gridview

programming interfaces for these controls

how to complete the master/Detail View

This article uses the following technologies:
Asp. net, Asp. NET 2.0, C #

Code download:
gridview.exe (124kb)

Content on this page
Gridview and DataGrid
Gridview and data source controls
Gridview Object Model
Gridview event
Display, sort, and paging
Edit data
Detailsview Control
Formview Control

Despite the rich and powerful programming interfaces, ASP. NET 1.XThe DataGrid Control still needs to write a lot of custom code to process common operations, such as paging, sorting, editing, and deleting data. For example, when you click to save or cancel changes, the DataGrid Control can trigger events but does not provide more functions. If you want to store changes to a continuous media (such as a database), you must handle the updatecommand event, retrieve the changed value, write an SQL command, and submit updates from there.

The DataGrid control limits the event triggered by normal data operations because it is an unknown control of the data source and can be bound to any enumerated data object. To perform data operations (such as update or delete), you must directly connect to a specific data source. In ASP. NET 1.XBy writing application-specificProgramTo solve this problem.

ASP. NET 2.0 improves the Data Binding architecture and introduces a new series of components (Data Source objects) as a bridge between data binding controls and ADO. Net objects. These source objects are upgraded to a slightly different programming model, providing new features and new members. Your ASP. NET 2.0 application should use the latest Grid Control-gridview to display data reports. The DataGrid control is still supported, but the DataGrid cannot fully utilize the specific functions of the data source component.

The gridview control is the successor of the DataGrid and extends the functionality of the latter in several aspects. First, it fully supports data source components and can automatically process data operations such as paging, sorting, and editing, provided that the bound data source object supports these operations. In addition, the gridview control has some superior functions than the DataGrid. In particular, it supports multiple primary key fields, discloses some user interface improvement functions and a new model for handling and canceling events.

The gridview comes with a pair of complementary View Controls: detailsview and formview. With the combination of these controls, you can easily create a master/Detail View, with only a small amount of code, and sometimes no code at all.

Gridview and DataGrid

In ASP. NET 2.0, the class hierarchies of data-bound controls are compared to ASP. NET 1.X. In version 2.0, all controls, regardless of their actual implementation process and user interface features, are derived from the same base class (basedataboundcontrol class. Figure 1 shows the new class relationship diagram. DataGrid and other 1.XVersion controls (such as repeater and datalist) are not included in the graph. Inheritance tree of these existing controls and ASP. NET 1.X. In particular, repeater inherits webcontrol, while datalist and DataGrid inherit basedatalist. As shown in 1, The gridview is a composite data binding control that shares a combination of methods and attributes with all other data binding controls, including dropdownlist, detailsview, and ListBox.

Figure 1 ASP. NET class relationship diagram

The advanced functions of the gridview and DataGrid controls are similar, but the basics are different. The gridview retains the object model of the DataGrid as much as possible, so that it can be easily transplanted from the existing page. However, the DataGrid-based code is not 100% compatible with the new gridview-based code.

Another major difference between the DataGrid and the gridview control is the adaptive user interface. And 1.XThe version of the DataGrid is different, and the gridview can also be displayed on mobile devices. In other words, you can use the same grid control for desktop pages to generate reports on mobile devices. The DataGrid of Version 2.0 can also be displayed automatically, but its UI functions are not rich in the gridview.

In ASP. NET 2.0, the improved DataGrid Control supports general controls such as themes and personalization. In addition, the new DataGrid control can be filled by a data source control. Remember that the DataGrid bound to the data source object can only be used to read data. Some user-defined code is still required to modify the underlying data source. The gridview control can use the underlying data source function to automatically delete or update records. Note: The gridview control also supports the traditional binding mechanism based on the datasource attribute and the databind method. Although this binding mechanism is fully supported, such programming practices are not encouraged.

Back to Top

Gridview and data source controls

So what is the data source control? OnJune 2004Phase IMsdnMagazineASP. NET 2.0. In short, a data source control is a set of Microsoft. NET Framework classes that facilitate bidirectional binding between data storage and data binding controls. Existing controls (such as DataGrid) and new data binding controls (such as gridview) can be bound to a data source even though their binding capabilities are different.

A Data Source Control represents the main functions of a Data source: selection, insertion, update, and deletion. The data source control can represent any Data source: From the relational data source library to XML files, from streaming data to business objects. If a brief introduction reminds you of the. NET hosting provider, see Figure 2.

Figure 2 data source control, gridview, and Data Source

The data source control can be located at the upper layer of some. NET data providers, forming an intermediate layer between the data binding control and the data source. The data source control also exposes a public interface that provides basic operations. Some data binding controls, especially the gridview control, bind these commands with other data-related operations to appropriate automatic editing.

The data source control uses its attributes and methods to publish the bound content in a group of named views. The idatasource interface provides a basic function set for retrieving data views from a data source. All data source controls implement this interface. ASP. NET 2.0 provides some built-in data source controls, suchFigure 3.Figure 3The data source controls listed are classified into two types: List and hierarchical components. The sitemapdatasource and xmldatasource components are hierarchical data source controls used for hierarchical components such as the Treeview and menu controls. Other components are used to manage list data.

Figure 4The code in shows how to bind the gridview and DataGrid to the same data source control on an example Page. In ASP. NET 2.0, This is the recommended data binding method. The sqldatasource control is characterized by an arbitrary combination of the seleconstring attribute plus the selectcommand, updatecommand, insertcommand, and deletecommand attributes. All attributes are in the string format and reference command text with optional parameters:

<Asp: sqldatasource runat = "server" id = "mysource" connectionstring = "Server = (local); database = northwind; Integrated Security = sspi; "selectcommand =" select * from employees where employeeid> @ minid "> <selectparameters> <asp: controlparameter name = "minid" controlid = "empid" propertyname = "text"/> </selectparameters> </ASP: sqldatasource>

Each data source control is represented by a unique ID. ID is the link between the data binding control and the data source control. Use the performanceid property to bind a gridview to a data source control. For example, when the grid needs to obtain data, it executes the selectcommand SQL command associated with the sqldatasource control. When the grid needs to update or delete a record, execute the corresponding updatecommand or deletecommand SQL command. If such a command does not exist, an exception is thrown. Internally, when a user deletes or updates a record, the gridview is like 1.XThe current version of DataGrid triggers events. However, unlike the DataGrid, The gridview defines internal handlers for these events. The default handler retrieves the commands defined by the bound data source to process and execute these operations.Figure 4Note: you do not need to write code after you mark the grid display or update data. In more complex cases, you may need to write some code.

Figure 5 gridview and DataGrid

The data source control and the gridview control are usually used to bind data without code. Figure 5 showFigure 4.

In ASP. NET 2.0, in addition to datasource and datamember, The DataGrid also discloses the performanceid attribute. The performanceid property connects the DataGrid to a valid data source object defined on the same page. However, the DataGrid does not provide the same level of automatic operations as the gridview. When you click to update a record, the DataGrid triggers the updatecommand event. In addition to the updating and updated events, the gridview also retrieves and executes the data source update command, allows you to customize the information sent to the data source control.

Back to Top

Gridview Object Model

The overall result of the gridview and the DataGrid looks similar. Some common elements have been renamed, and some common functions now require different syntaxes. In short, if you are familiar with the DataGrid control, you can use the gridview immediately.Figure 6A detailed list of new elements that form the gridview (note that some elements, such as detaillinkstyle, are only used to display grids on mobile devices ). The row element is displayed through the instance generated by the gridviewrow class in the rows set. The gridviewrow class maps to the datagriditem class, while rows explicitly replaces the project set of the DataGrid. The row type is represented by datacontrolrowtype enumeration to indicate the position and role (for example, footer, header, page navigation, and data row ). Gridview also introduces a new concept-Row Element state. The row State is represented by the enumerated values marked by datacontrolrowstate-the normal value is edit, and the optional values are insert and selected. Interestingly, these two enumeration types happen to be shared by all data View Controls (gridview, detailsview, and formview.

In addition to introducing elements that conform to adaptive display, the gridview has only one new element of other types-Empty data rows. When the gridview is bound to an empty data source, some default content is displayed selectively to provide feedback to users. In this case, the displayed content depends on the content of the new empty data Row Element. You can set the content of this row through an attribute (emptydatatext) or a template (emptydatatemplate.

The properties of the gridview control are divided into three types: behavior, visual setting, and status.Figure 7Lists some properties of the gridview. View the new attributes, including enablesortingandpagingcallbacks, emptydatatext, and useaccessibleheader, And the renamed or adapted attributes. The latter implements the functions supported by the DataGrid.

The programming model is slightly different from the button column. In ASP. NET 1.XIn the DataGrid, you have to create an edit button-editcommandcolumn by adding a specific column type. To create a delete or select button column, you must add a common button column and predefine a command name. The gridview object is more consistent and concise. It is based on three new Boolean attributes: autogenerateeditbutton, autogeneratedeletebutton, and autogenerateselectbutton. When any attribute is set to true, an edit, delete, or SELECT command button column is added to the grid. For example, when the autogenerateeditbutton attribute is set to true, a column with the edit button is automatically added to each data row in the grid. You can also manually add these buttons by adding a commandfield object to the column set. The columns attribute lists the column objects, which are similar to the objects listed in the columns attribute of the DataGrid. Based on Customer feedback, several helper attributes are added. In particular, you can now store multiple key values for each display row. In fact, the datakeyfield string attribute of the DataGrid has been extended to an array of field names. The new attribute is named datakey, which is used to store a string array composed of field names. This string array uniquely identifies a data row. Datakey is an array of values of a Specific Row. It returns the set of datakey objects. Each datakey object contains a key name value. The number of datakey objects of datakey is the same as the number of displayed rows of the gridview.

Sortdirection and sortexpression track the current grid sorting. These attributes are used internally for automatic flip sorting, marking the current sorting order of the grid. Each object's pagersettings group contains all the attributes for configuring the user interface, behavior, and page navigation location. Currently, the navigation modes supported by page navigation include not only the first line and the last line, but also the next line and the last line.

The gridview control can also use a callback-based lightweight mechanism for sorting and paging. You can enable or disable the enablesortingandpagingcallbacks Boolean attribute. When you click the sort or paging link to enable callback, The gridview requests the sorting data or the next page without sending back the visible page. (There is a round-trip process, but there is no page refresh, so you do not know .) Note that this feature has a warning: When the option in the gridview is enabled, the selected index is retained on the new page. If there is a detailed page associated with it, the selected content will be out of sync. Processing events such as pageindexchanging does not work, because if callback is not enabled, these events cannot be raised. Finally, remember that the paging and sorting mechanisms of the callback driver must use Microsoft Internet Explorer 5.0 and later versions.

Back to Top

Gridview event

The method used by the gridview control is different from the databind method we are familiar. In ASP. NET 2.0, many controls and the page class use pre-load/post-load event pairs. Key operations in the lifecycle of a control are encapsulated in one event. One is triggered before an operation occurs, and the other is triggered immediately after the operation is completed. The same is true for the gridview class.Figure 8The new event list is displayed. The use of events to advertise operations greatly enhances programming capabilities. For example, by hook the rowupdating event, you can check the update content of the new value. You may want to handle the rowupdating event through HTML encoding before the value provided by the client persists to lower-level data storage. This simple technique helps avoid malicious script injection.

The pre/post event enables you to cancel an event based on runtime conditions. See the following code snippet:

Void pageindexchanging (Object sender, gridviewpageeventargs e) {// is this the sensitive page? (> 4) bool issensitivepage = (E. newpageindex> 4); If (issensitivepage & (user. Identity. Name! = "Username") E. Cancel = true; return ;}

Cancellation is a read/write Boolean attribute that exists in all event parameter classes derived from canceleventargs. Many event parameter classes in the gridview inherit canceleventargs, which means all these events can be canceled. The cancel attribute value is usually set to false when a "pre" event is triggered. When processing an event, you can check some conditions and select "cancel event" by setting the cancel attribute to true. For example, when the current user is not authorized to view a page with an index greater than 4, the code snippet cancels the conversion to a new page.

Back to Top

Display, sort, and paging

A grid is usually used to display the database query results. Displaying results using the gridview control is easier than ever. You only need to create a data source object, provide the connection string and query text, and assign the data source ID to the performanceid attribute of the gridview. During running, the gridview is automatically bound to the data source to generate the correct data column. By default, all queried columns are displayed in the grid.

Like the DataGrid Control, the gridview also supports customizing column fields in the columns set. If you only want to display a subset of the retrieved data fields, or want to customize the display appearance, you can use an object representing the display data column to fill the columns set. Gridview supports multiple column types, including new check boxes and image column types:

<Columns> <asp: boundfield datafield = "productname" headertext = "product"/> <asp: checkboxfield datafield = "discontinued" headertext = "discontinued"/> <asp: buttonfield buttontype = "button" text = "buy"/> <asp: hyperlinkfield text = "more info... "datanavigateurlfields =" productid, discontinued "datanavigateurlformatstring =" more. aspx? Id = {0} & disc = {1} "/> </columns>

Figure 9 shows the active mesh configured to use the fields listed in the Code. The Class Name of the gridview column is slightly different from the corresponding class name in the DataGrid interface. The suffix "column" is basically replaced with the suffix "field ". Except for name changes, the behavior that matches the column Class is almost the same. Some new column types make it unnecessary to use templates frequently. For example, the checkboxfield column uses a check box to display specific data fields, and the improved hyperlinkfield column provides the long-awaited function-supporting multiple URL parameters. As shown in the code snippet, The datanavigateurlfields attribute receives a list of field names separated by commas and merges them into the text of the datanavigateurlformatstring attribute.

Figure 9 gridview with an active field

Note the differences between buttonfield and commandfield. Both columns Add a button to the mesh user interface, but commandfield is used to display command buttons for selection, editing, insertion, or deletion. Buttonfield only represents the field displayed as a button. Finally, the gridview can embed images through the imagefield column type.

<Asp: imagefield datafield = "photo" headertext = "picture"/>

Figure 10 shows the active imagefield column, which is located in the photo field of the northwind employee table. Interestingly, imagefield uses the ASP. NET 2.0 dynamicimage control to display images from both databases and URLs. In editing mode, a browse button is displayed in the imagefield column to locate the new local file to be uploaded.

Figure 10 image field Column

The template column is also supported. The required syntax is equivalent to ASP. NET 1.XThe DataGrid of is similar:

<Asp: templatefield headertext = "product"> <itemtemplate> <B> <% # eval ("productname ") %> </B> <br/> available in <% # eval ("quantityperunit") %> </itemtemplate> </ASP: templatefield>

Interestingly, the syntax of data binding expressions allowed by ASP. NET 2.0 is more concise. In ASP. NET 1.XThe following expression must be used to generate templated content: databinder. eval (container. dataitem, "fieldname") because a smaller data binding mechanism is used, you can avoid using static eval methods in the databinder class, instead, call the new eval protection method defined by the page class. You pass the calculated field name and method to eval to determine the current data item and prepare a regular call through databinder. eval.

Eval is declared as a protection method of the templatecontrol class. Both page and usercontrol are derived from this class. A class that really represents a. aspx activity page is an instance of a class derived from page; therefore, it can call a protected method. The same is true for the ascx user control.

If the focus is to display pure data, a completely new grid control like the gridview is not required. Of course, now you only need a small amount of code or no code to bind the data source control to the gridview, but is it necessary to replace the DataGrid alone? If the answer is no, consider sorting and paging.

In the gridview control, you only need to enable the Auto flip sorting and paging functions by enabling the allowpaging and allowsorting attributes. If ASP. NET 1.XIf you have tried this operation, you can get to know about this feature.

Figure 11 pagination and sortedgrid of activity

Figure 11 shows a pagination and sorting grid.Figure 12Displays the complete code for this grid. (It is worth noting that C # code is only required to mark the column header to indicate the sorting direction .) Therefore, sorting and paging can run normally without writing code. Use the cecemode attribute to control the data retrieval model of sqldatasource. The valid value types are dataset (default value) and datareader. When the datasourcemode is dataset, the data source control may selectively cache the results of the SELECT command. This makes the gridview suitable for a wide range of use cases. The control can provide code-less sorting, filtering, and paging functions. Cache is disabled by default, so it must be enabled on the data source control.

Caching data in the memory can greatly improve the performance, but the data may be somewhat fragile. You must weigh the advantages and disadvantages because if the system memory runs less efficiently, the cache object will automatically discard the least amount of data used. In addition, in ASP. NET 2.0, the sqldatasource control may selectively establish an automatic dependency with the database for immediate detection of data changes. This ensures that the latest data is always displayed. For more information about the data source control function, seeArticle. When the sqldatasource control is used to retrieve data in the datareader model, the idatareader object is used to retrieve data. It is a forward-only, read-only, and flow cursor.

Back to Top

Edit data

One of the biggest disadvantages of the DataGrid Control-on the contrary, it is one of the biggest advantages of the gridview control and is the ability to process data source updates. When the bound data source supports updating, the gridview can automatically perform data operations to provide a real out-of-box solution. Data source controls provide these functions through Boolean attributes (such as canupdate, candelete, and cansort.

For the gridview control, data editing means local editing and deletion of records. As mentioned above, in-place editing means that the grid supports changing the currently displayed records. To enable local editing of the gridview, you must start the autogenerateeditbutton Boolean attribute:

<Asp: gridview runat = "server" id = "mygridview" performanceid = "mysource" autogenerateeditbutton = "true"> • </ASP: gridview>

When the autogenerateeditbutton attribute is set to true, the gridview displays the appended column, the leftmost column in 13. Click the edit button of a row to place the row in edit mode. When a row is in editing mode, each bound field of a non-read-only row displays an appropriate input control, usually a textbox. When you click Update, The gridview triggers the rowupdating event and checks the canupdate attribute of the data source. If the return value of canupdate is false, an exception is thrown. Otherwise, create and configure a command object after the updatecommand attribute of the data source object.

Figure 13 edit column of the gridview

You do not need to use ADO. Net or worry about how to use commands or connect even if you only define the command structure to define statements and allow controls to perform other operations. To retain changes when you click Update, write the following code:

<Asp: sqldatasource runat = "server" id = "mysource" connectionstring = "Server = ...; database = northwind; integratedsecurity = sspi; "updatecommand =" Update employees setfirstname = @ firstname, lastname = @ lastnamewhere employeeid = @ employeeid "> </ASP: sqldatasource> <asp: gridview runat = "server" id = "mygridview" performanceid = "mysource" datakeynames = "employeeid" autogenerateeditbutton = "true"> • </ASP: gridview>

The updatecommand attribute of the data source is set to the SQL command used by the gridview. You can use any number of required parameters. If you use a special naming rule, the parameter value can be automatically parsed. The parameter representing the updated field (for example, firstname) must match the datafield attribute name of the grid column. The where clause used to identify a work record must match the datakeynames attribute, which is the key field of the display record. Finally, consider this situation: If the updatecommand is not defined but changes are submitted, the canupdate return value is false and an exception is thrown. The rowupdated event sends a signal to notify the end Of the update command. The number of rows updated by the update command can be retrieved in the affectedrows attribute of the rowupdated event parameter.

The gridview automatically collects the value of the input field and fills the name/value pair dictionary. This dictionary indicates the new value of each row field. The gridview also exposes a rowupdating event, allowing you to modify the value of the object being passed to the data source. In addition, before the update operation is triggered on the relevant data source, the gridview will automatically call page. isvalid. If the returned value of page. isvalid is false, the operation is canceled. This is particularly useful for using custom editing templates, including validators.

The row deletion operation is similar to this operation. The following SQL command is the valid CONTENT OF THE deletecommand attribute of a data source object:

Delete employees whereemployeeid = @ employeeid Note: if you cannot delete a record due to database constraints, the delete operation will fail. For example, if a child record references a parent record through a certain link, the parent record cannot be deleted. In this case, an exception is thrown.

The gridview control does not automatically support inserting data into the data source. Without this function, it is entirely because the implementation of the gridview does not depend on the features and features of the underlying data source. In fact, the data source object provides a caninsert attribute and supports an insertcommand attribute. Note that you can use the combination of the gridview and detailsview controls to implement this function.

Back to Top

Detailsview Control

Many applications need to act on one record at a time. In ASP. NET 1.X. Creating a single record view is possible, but you need to write your own code. First, you need to obtain the record, then bind the field to the data binding form, and select the paging button to browse the record. I have compiled three installation programs for the cutting edge column to solve this problem-April 2002, May, and June.

When a master/Detail View is generated, the content of a single record is often displayed. Generally, you can select a master record from the grid to allow the application to trace all available fields. By combining the gridview and detailsview, you can write a small amount of code to generate a hierarchical view.

The detailsview control can be automatically bound to any data source control and used for its data operation set. Controls automatically pagination, update, insert, and delete data items of the underlying data source, as long as the data source supports these operations. In most cases, you do not need to write code to create these operations, as shown below:

<Asp: detailsview runat = "server" id = "det" performanceid = "mysource" autogenerateeditbutton = "true" autogenerateinsertbutton = "true" comment = "true" allowpaging = "true" headertext = "employees "> <pagersettings mode =" Courier "firstpageimageurl =" images/first.gif "lastpageimageurl =" images/last.gif "nextpageimageurl =" images/next.gif "placement =" images/prev.gif "/> /ASP: detailsview>

The user interface of the detailsview control can be customized by using data fields and types. The method is similar to that of the gridview. Detailsview does not support custom templates, because this special feature is fully constructed in the new formview control. Detailsview has a command bar that displays any combination of the edit, delete, and new buttons. When you click Edit or new, the control displays edit or insert mode, and the field content is displayed in the text box. The working mode can be controlled through the mode and defaultmode attributes.

The detailsview control can be used to implement a master/Detail View without code. In addition to the edit and delete buttons, The gridview control supports the select button, which is also predefined. You can enable this button for each row by setting the autogenerateselectbutton attribute to true. When you click this button, enter the selected status in the current row and assign the index value starting from 0 to the selectedindex attribute of the gridview. In addition, the gridview control triggers the selectedindexchanged event. Applications can hook up this event and execute custom code.

In ASP. NET 2.0, if you want to generate a master/Detail View, you do not need to process the selectedindexchanged event. You can drag a gridview control and a detailsview control to the page and bind the two to a data source. To generate a master/Detail View without code, bind the Detail View control to the data source represented by the selected record, as shown below:

<Asp: sqldatasource runat = "server" id = "mydetailsource" • selectcommand = "select * from MERs" filterexpression = "customerid = '@ mermerid'"> <filterparameters> <asp: controlparameter name = "customerid" controlid = "mastergrid" propertyname = "selectedvalue"/> </filterparameters> </ASP: sqldatasource>

The filterexpression attribute of the data source object is the WHERE clause defined for the basic query specified by selectcommand. Parameter values can be specified in multiple ways, including directly binding a control property. The object sets the @ mermerid parameter to the value stored in the selectedvalue attribute of the primary grid control.Figure 14The code shows how to configure the master Grid Control and detailed view control. Figure 15 shows the activity page. Note that no program code is required to complete these functions.

Figure 15 active master Grid

Back to Top

Formview Control

Formview is a new data binding control, which is used as a template version of detailsview. It selects a record display from the relevant data source each time and provides a paging button to move between records. Unlike the detailsview control, formview does not use data control fields, but allows users to define the display of each project through a template. Formview supports any basic operations provided by its data source.

The formview control is designed as a commonly used update and insert interface. It cannot verify the data source architecture and does not support advanced editing functions, such as drop-down of foreign key fields. However, it is easy to use templates to provide this function. Formview and detailsview have two functional differences. First, the formview control has the itemtemplate, edititemtemplate, and insertitemtemplate attributes, but neither detailsview. Second, formview lacks the command line-toolbar for grouping available functions. Unlike the gridview and detailsview controls, formview does not have its own default display layout. At the same time, its graphical layout is completely customized by the template. Therefore, each template contains all the command buttons required for a specific record. The following code snippets are typical examples of embedding a formview in a page.

<Asp: formview id = "empdetails" runat = "server" performanceid = "mysource" allowpaging = "true"> <itemtemplate> • </itemtemplate> <edititemtemplate> • </ edititemtemplate> <insertitemtemplate> • </insertitemtemplate> </ASP: formview>

Figure 16 shows a page using the formview control. The Edit button uses the command name Edit <ASP: button> Element. This will cause formview to be converted from read-only mode to edit mode and displayed using the defined edititemtemplate. The new command will force the control to be converted to the insert mode to display the definition of insertitemtemplate. Finally, if you add the button named Delete to the Project template, When you click it, formview calls the DELETE command of the data source.

Figure 16 formview Control

How to retrieve data to update or insert a record? You can use a new data binding keyword bind, which is specially designed for Bidirectional binding:

The BIND keyword is used to display data like eval and to retrieve input values when updating or inserting a record. In addition, BIND is very useful for templatefields used by gridview and detailsview.

Bind stores the property values of the bound control into a value set. The formview control automatically retrieves and uses this set to combine the list of parameters used to insert or edit commands. The parameter passed to bind must match the field name of the Data container. For example, the text box in the previous code snippet stores the value of the remarks field. Finally, remember that the edit and insert templates must contain buttons for saving changes. This is a common button-the update and insert used for saving and the cancel used to discard the operation.

The formview event works in the same way as detailsview and gridview. Therefore, if you want to process more complex operations such as data preprocessing or post-processing (such as filling down the drop-down box), you should write appropriate event handlers for events such as itemcommand, iteminserting, and modechanging.

Back to Top


Data Binding controls are essential components of most web applications. Data Binding controls should be simple but powerful. Ideally, they should provide advanced features with few click operations and a limited number of code. Although ASP. NET 2.0 is still in use, its new-generation data binding control meets this requirement. ASP. NET 1.XThe main disadvantage of data binding is that you need to write too much code for common data operations. This point has been solved with the introduction of the data source object and the gridview control. Detailsview and formview are perfect supplements to the gridview, representing ASP. NET 1.XSignificant improvements to the data toolkit.

Dino Esposito is a lecturer and consultant who works in Italy. He is programming ASP. net and introducing ASP. NET 2.0 (both from Microsoft Press), who spent most of his time teaching about ADO. net and ASP. net Courses and presentations at the conference. You can contact Dino or access his Web diary through the .

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: 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.