[Asp.net tour] -- DataList of data binding controls

Source: Internet
Author: User

The previous blog discussed the basic usage of the Repeater control. It is the most basic data binding control and only provides the data binding function. After skillfully using the Repeater control, other similar data binding controls are simple. Next, let's continue with the content of the previous blog. Today we will discuss the basic usage of DataList.

 

I. DataList for binding controls


This control can display fields of various data sources in a custom format, and its display data format is defined in the created template, you can create templates for items, alternate items, selected items, and edit items. The control can also use the title, footer, and delimiter template to customize the overall appearance, and display multiple data rows in one row. Although the DataList control has great flexibility, it does not support data paging. programmers must compile their own methods to complete the paging function. It is only used for data display and cannot be edited, inserted, or deleted.
Advantages:Display Data in custom formats.
Disadvantages:Pagination is not supported. Edit and insert.

 

1. Introduction to DataList


As mentioned above, the DataList control not only flexibly displays data, but also supports editing, inserting, and deleting operations. The basic template for displaying data is essential. The same control also provides developers with basic templates. In addition, DataList not only provides basic ItemCommand events, but also encapsulates Delete, cancel, edit, and update events. By binding data to the EditItemTemplate template, you can easily enter the editing status. The specific method will be described below.

The usage of basic templates and events has been discussed in the previous article and will not be discussed in depth here.

 

2. Control usage skills

 

1. Basic operations-add, delete, and modify

 

The following code example uses Asp.net to add, delete, and modify data. The DataList control encapsulates basic deletion and modification templates, but does not inherit the insertion function. In this example, the insertion is implemented using the Literal control of Asp.net. The specific implementation method is as follows.
Delete page:

 

Add page:

Edit page:


Front-end code: the basic usage of the Repeater control is the same. The difference is that a new editing template is added, and data is bound to the editing template. You only need to jump to the editing template when editing the template. In the code, the Literal control is added to the ItemTemplate of the basic template. When you click the Add button, a new row is dynamically added in the background and a data control is added to the new row. The specific background code is as follows.

 

        
ID Content Edit
<% # Eval ("id") %> <% # Eval ("name") %> DeleteEditAdd

Background code: the operation to add a new row is specified in the ItemCommand event. The code of the new row is added to the Literal control to add a new row and specify a control for the new row. In addition, the basic Editing Command is written in a separate event, because DataList provides developers with basic operation events. To enter a certain state, you only need to set the ItemIndex value of the State.

Protected void Page_Load (object sender, EventArgs e) {if (! Page. isPostBack) {string strName = string. empty; // declare the added content try {// obtain the content to be added strName = Request. queryString ["name"]. toString () ;}catch {}// determines if the content to be added is not empty, the add operation if (strName! = String. empty) {this. insert (strName );} //************************************** * ******************************** // PagedDataSource is achieved new PagedDataSource (); // declare the page class // set the page attributes. allowPaging = true; Pam. pageSize = 3; Pam. dataSource = this. getDT (). defaultView; Pam. currentPageIndex = pageIndex-1; //************************************** * ****************************** // bind the paging data source this. dataList1.DataSource = PPS; this. dataList1.DataBind ();}}////// Add new data row content //////Get the content to be inserted private void Insert (string strName) {// Insert the new content using (SqlConnection con = this. getSqlCon () {con. open (); // Open the database connection // set the command object SqlCommand sqlcom = new SqlCommand (); sqlcom. connection = con; sqlcom. commandText = "insert match values (@ name)"; // Add the sqlcom. parameters. add (new SqlParameter ("@ name", strName); // insert sqlcom. executeNonQuery ();}}////// Obtain the bound data source //////
 
  
DataTable, the content obtained from the match table
 Private DataTable GetDT () {DataTable dt = new DataTable (); // declare the database table // obtain the data source using (SqlConnection con = this. getSqlCon () {con. open (); // declare the data source command SqlCommand sqlCom = new SqlCommand (); sqlCom. commandText = "select * from match"; sqlCom. connection = con; SqlDataAdapter sqlDa = new SqlDataAdapter (sqlCom); SqlCommandBuilder sqlCb = new SqlCommandBuilder (sqlDa); sqlDa. fill (dt);} return dt ;}////// Declare the database link object //////
 
  
SqlConnection, returns the database connection object
 Private SqlConnection GetSqlCon () {SqlConnection sqlCon = new SqlConnection ("server =.; database = myblog; uid = sa; pwd = 1"); return sqlCon ;}////// Edit command event /////////Protected void DataList1_EditCommand (object source, DataListCommandEventArgs e) {this. dataList1.EditItemIndex = e. item. itemIndex; // set the edited index row // re-bind the data source this. dataList1.DataSource = this. getDT (); this. dataList1.DataBind ();}////// DELETE command event /////////Protected void DataList1_DeleteCommand (object source, DataListCommandEventArgs e) {if (e. commandName = "Delete") {string id = e. commandArgument. toString (); // obtain the ID of the row to be deleted // execute the DELETE command using (SqlConnection con = this. getSqlCon () {con. open (); SqlCommand sqlcom = new SqlCommand (); sqlcom. connection = con; sqlcom. commandText = "delete from match where id = @ id"; sqlcom. parameters. add (new SqlParameter ("@ id", id); sqlcom. executeNonQuery ();} // rebind data this. dataList1.DataSource = this. getDT (); this. dataList1.DataBind ();}}////// Cancel the update event /////////Protected void DataList1_CancelCommand (object source, DataListCommandEventArgs e) {if (e. commandName = "Cancel") {this. dataList1.EditItemIndex =-1; // rebind data this. dataList1.DataSource = this. getDT (); this. dataList1.DataBind ();}}////// Update button event /////////Protected void DataList1_UpdateCommand (object source, DataListCommandEventArgs e) {// if it is an update command, the update command if (e. commandName = "Update") {int intId = int. parse (e. commandArgument. toString (); // obtain the index number of the updated row string strname = (TextBox) e. item. findControl ("name ")). text; // obtain the updated content // update the database value using (SqlConnection sqlcon = this. getSqlCon () {sqlcon. open (); SqlCommand sqlcom = new SqlCommand (); sqlcom. commandText = "update match set name = @ name where id = @ id"; sqlcom. connection = sqlcon; SqlParameter [] sqlParam = new SqlParameter [] {new SqlParameter ("@ name", strname), new SqlParameter ("@ id", intId)}; sqlcom. parameters. addRange (sqlParam); sqlcom. executeNonQuery ();} // jump to this page after the update is complete. dataList1.EditItemIndex =-1; // rebind data this. dataList1.DataSource = this. getDT (); this. dataList1.DataBind ();}}////// Event sending back command /////////Protected void DataList1_ItemCommand (object source, DataListCommandEventArgs e) {// if the command name is Add, a new line if (e. commandName = "Add") {Literal partition = (Literal) e. item. findControl ("litAdd"); // get the object on the page // Add the new line tag StringBuilder strAdd = new StringBuilder (""); StrAdd. append ("cancel"); strAdd. append ("OK"); strAdd. append (""); // adds the new line tag to html. text = strAdd. toString ();}}

 

2. Paging implementation


The paging effect is similar to that of the Repeater control. Add the Literal control on the front-end page, and use the PagedataSource class in the background to paging the data.
Front-end code: Add a pagination div tag at the end of the page, and add the Literal control to the div. The link address of the tag in the control is dynamically specified in the background.

 <Script src = "Scripts/jquery-1.7.1.js"> </script> <script type = "text/javascript" language = "javascript"> $ (function () {$ ("# OK" ).css ("text-decoration", "underline" ).css ("color", "blue"); $ ("# CancelInsert "). attr ("href", "http://blog.csdn.net/zhang_xinxiu/article/details/Default.aspx") ;}); function InputKey () {var vartext = document. getElementById ("name "). value; $ ("# OK "). attr ("href", "http://blog.csdn. Net/zhang_xinxiu/article/details/Default. aspx? Name = "+ vartext) ;}</script>  


Background code: each time you request data from the background, the link address of the page is re-specified for the tag, so that PagedataSource can be linked to the desired page.

 

Protected void Page_Load (object sender, EventArgs e) {if (! Page. isPostBack) {int pageIndex = 1; // declaration page index try {// retrieve the index number pageIndex = int. parse (Request. queryString ["Page"]. toString (); // if it is the zeroth page, it will be assigned the first page if (pageIndex <0) {pageIndex = 1 ;}} catch {// the first page is displayed by default. pageIndex = 1;} // you can add if (strName! = String. empty) {this. insert (strName );} //************************************** * ******************************** // PagedDataSource is achieved new PagedDataSource (); // declare the page class // set the page attributes. allowPaging = true; Pam. pageSize = 3; Pam. dataSource = this. getDT (). defaultView; Pam. currentPageIndex = pageIndex-1; //************************************** * ****************************** // bind the paging data source this. dataList1.DataSource = PPS; this. dataList1.DataBind (); // Add the tab this. invalid. text = this. getPageBar (PPS );}}////// Add and set paging commands //////Paging data source ///
 
  
A tag containing paging connections
 Private string GetPageBar (PagedDataSource PPS) {string Page = string. empty; int intCurrent = pds. currentPageIndex + 1; // set the home Page url if (intCurrent = 1) {Page + = "home Page"; // escape character: \ "Double quotation marks} else {Page + ="

 

Download the sample code: DataList.

 

Iii. Comparison and sublimation

 

Compare the two data binding controls in the previous article. For the Repeater control, the most basic binding control developed by Microsoft only provides developers with basic event streams and basic templates, each subitem can be compiled by the developer without generating redundant code. The only drawback is that Microsoft does not encapsulate paging, editing, and other functions. To implement this function, you must write it yourself.

Compared with the Repeater control, the DataList control not only encapsulates events such as edit, delete, update, and cancel on the basis of the Repeater, but also adds the Selectedtemplate template, it is able to write the Display Effect of selected rows in the background code, and its application is flexible. What is lacking in the United States is that it does not have the function of encapsulating pages and inserting data. It can only be compiled by developers themselves, in addition, the redundant code is generated after the DataList style is designed using a visual window, which is not easy to read.

In short, they both have their own advantages and disadvantages when used. If you only want to bind and display data, the Repeater control is of course our first choice. Of course, if you have operations such as editing and deleting, if you want to design the Binding style in advance, use DataList.

 

Conclusion

 

Compared with the two controls, they both have advantages and disadvantages. Isn't there any perfect binding controls? Of course not ,. NET encapsulates multiple data binding controls. The preceding two controls are frequently used in programming. The ListView control provides complete functions, its usage will be discussed in the next article.

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.