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

Source: Internet
Author: User

Introduction


In the previous articles about AJAX, AJAX technology can be used to develop highly-efficient website applications, however, it is far from enough to have AJAX technology for B/S project development. More things will be learned from B/S, however, compared with the complex logic structure of C/S, B/S is still very simple during development.

Data Binding controls are often used when developing B/S projects ,. NET platform has well encapsulated these controls, as long as a slightly experienced programmer can quickly use these data controls, so the following articles will discuss data controls, first, we will discuss the basic usage of ListView, GridView, Repeater, and DataList controls from the details of the data control, and make a comprehensive analysis and summary of these controls at the end of a series of articles after the meeting.

I. Repeater for binding controls


. NET encapsulates a variety of data binding controls, such as GridView and DataList, but this article will start with Repeater, because Repeater only provides basic data binding templates, no built-in paging and other functions, so it is the most primitive data binding control, as long as you can skillfully use the Repeater control other binding control is very easy.

 

1. Repeater Introduction

 


The Repeater control is a list of basic templated data. It does not have the same visual design format or style as the GridView control. Therefore, all formats, formats, and style tags must be explicitly declared in the control template during development. In addition, the Repeater control does not have built-in functions such as selection, sorting, editing, and paging. It only provides basic data binding, but it provides developers with ItemCommand events, this event supports sending and receiving commands in the control.
To bind data, templates are essential. The Repeater control also supports data templates. You can also add the desired tags to the template. Its main usage is as follows:

Note: Each Repeater control must define an ItemTemplate.



2. Control usage skills

 


The above describes the basic usage of Repeater and some basic features of Repeater. Next we will use several classic examples to apply the Repeater control.

 

1. Delete and edit data binding

 

In this example, the foreground and background of Asp.net are used to display data and edit and delete data.

Delete page:


Edit page:


Front-end code: After you click the edit button, the editing page is displayed. The page is controlled by two Panel controls. You can pass the ID number to determine whether the displayed page is edit or delete, in addition, the front-end Code sets the CommandArgument attribute of the control to pass the ID number to be judged by the background.

 

 

 

 

Background code: ItemCommand and ItemDataBound are two important events in the background code. ItemCommand is responsible for receiving the button commands passed in at the foreground and setting the id passed in at the background based on the command parameters, verify the id in ItemDataBound to determine whether to switch the display Panel.

 

Using System; using System. collections. generic; using System. data; using System. data. sqlClient; using System. web; using System. web. UI; using System. web. UI. webControls; namespace WebApplication4 {public partial class EditPage: System. web. UI. page {private int id = 0; // Save the id number of the specified row operation ////// Bind data when loading the form /////////Protected void Page_Load (object sender, EventArgs e) {if (! Page. IsPostBack) {this. DataBindToRepeater (); // bind data to the Repeater control }}////// Bind the data source to the Repeater control ///Private void DataBindToRepeater () {// use the using statement to connect to the database using (SqlConnection sqlCon = new SqlConnection ("server = .; database = MyBlog; uid = sa; pwd = 1 ") {sqlCon. open (); // Open the database connection SqlCommand sqlcom = new SqlCommand (); // create the database command object sqlcom. commandText = "select * from match"; // specifies the execution statement sqlcom. connection = sqlCon; // specify the Connection object for the command object this. userRepeat. dataSource = sqlcom. executeReader (); // specify the data source this for the Repeater object. userRepeat. dataBind (); // bind the data source }}////// Repeater control command event /////////Protected void userRepeat_ItemCommand (object source, RepeaterCommandEventArgs e) {// obtain the command text, determine the type of the command to be issued, and call the event if (e. commandName = "Edit") // Edit command {id = int. parse (e. commandArgument. toString (); // obtain the command ID} else if (e. commandName = "Cancel") // Cancel the update command {id =-1;} else if (e. commandName = "Delete") // command for deleting row content {id = int. parse (e. commandArgument. toString (); // obtain the ID number of the row to be deleted // Delete the selected row and re-specify the binding operation this. deleteRepeater (id);} else if (e. commandName = "Update") // command to Update the line content {// obtain the content and ID of the updated line string strText = (TextBox) e. item. findControl ("txtName ")). text. trim (); int intId = int. parse (Label) e. item. findControl ("lblID ")). text); // update the content of the Repeater control this. updateRepeater (strText, intId);} // rebind the control content this. dataBindToRepeater ();}////// Delete row content //////Delete the ID private void DeleteRepeater (int intId) {using (SqlConnection sqlCon = new SqlConnection ("server = .; database = MyBlog; uid = sa; pwd = 1 ") {sqlCon. open (); // Open the database connection SqlCommand sqlcom = new SqlCommand (); // create the database command object sqlcom. commandText = "delete from match where id = @ id"; // specify the execution statement sqlcom for the command object. connection = sqlCon; // specify the Connection object for the command object // create a parameter set and add SqlParameter sqlParam = new SqlParameter ("@ id", intId) to sqlcom ); sqlcom. parameters. add (sqlParam); sqlcom. executeNonQuery (); // specify the update statement }}////// Update the content in the Repeater control //////Modified content ///Private void UpdateRepeater (string strText, int intId) {using (SqlConnection sqlCon = new SqlConnection ("server = .; database = MyBlog; uid = sa; pwd = 1 ") {sqlCon. open (); // Open the database connection SqlCommand sqlcom = new SqlCommand (); // create the database command object sqlcom. commandText = "update match set name = @ str where id = @ id"; // specify the execution statement sqlcom for the command object. connection = sqlCon; // specify the Connection object for the command object // create a parameter set and add the SqlParameter [] sqlParam = {new SqlParameter ("@ str ", strText), new SqlParameter ("@ id", intId)}; sqlcom. parameters. addRange (sqlParam); sqlcom. executeNonQuery (); // specify the update statement }}////// Events that occur when the Repeater control is bound to data /////////Protected void userRepeat_ItemDataBound (object sender, RepeaterItemEventArgs e) {// checks whether the data in the Repeater control is a bound data source, if yes, the system will verify whether the edit operation is performed. // The ListItemType enumeration indicates that different items can be included in a list control, such as the DataGrid, DataList, and Repeater controls. If (e. item. itemType = ListItemType. item | e. item. itemType = ListItemType. alternatingItem) {// obtain the bound data source. Note that the above method uses sqlReader to bind the data source, so the following DbDataRecord method is used to obtain // if the data source to be bound is of the DataTable type, the following statement will return an error. system. data. common. dbDataRecord record = (System. data. common. dbDataRecord) e. item. dataItem; // data source verification method of the DataTable type // System. data. dataRowView record = (DataRowView) e. item. dataItem; // determine whether the data source id is equal to the current id. if the data source id is equal, it indicates that the userRepeat_ItemCommand event if (id = int. parse (record ["id"]. toString () {(Panel) e. item. findControl ("plItem ")). visible = false; (Panel) e. item. findControl ("plEdit ")). visible = true;} else {(Panel) e. item. findControl ("plItem ")). visible = true; (Panel) e. item. findControl ("plEdit ")). visible = false ;}}}}}


 

2. PageDataSource

Front-end code: uses the original html text and adds a Literal tag to dynamically add and specify html tags.

Page:

 

    

 

Background code: the data source of the Repeater control is a PagedDataSource object. When a page is loaded, the pagination attribute is dynamically specified for the object, and the Literal label is used to dynamically specify the link for each tab to jump to the page.

 

Using System; using System. collections. generic; using System. data; using System. data. sqlClient; using System. text; using System. web; using System. web. UI; using System. web. UI. webControls; namespace WebApplication4 {public partial class PageDemo: System. web. UI. page {private string id = ""; protected void Page_Load (object sender, EventArgs e) {if (! Page. isPostBack) {// set the index int pageIndex = 1 on the current page; try {// obtain the index number pageIndex = Convert. toInt32 (Request. queryString ["Page"]); // if the Page is 0th, it will jump to Page 1st if (pageIndex <= 0) {pageIndex = 1 ;}} catch {pageIndex = 1;} DataTable dt = this. getDataTable (); // obtain the bound data table PagedDataSource PPS = new PagedDataSource (); // create a data source object (pds. dataSource = dt. defaultView; // set the data source pds for the data source object. allowPaging = true; // The object allows pagination of the PNS. pageSize = 2; // set the size of the object per page. currentPageIndex = pageIndex-1; // set the current page of the data source // bind the paging data source control to the Repeater control this. repeater1.DataSource = PPS; this. repeater1.DataBind (); // use the Literal label to dynamically specify the link of each tab to jump to the page ltlPageBar. text = this. getPageBar (PPS );}}////// Obtain the link address of the jump page on each tag //////Paging data source object ///
 
  
Html text of the paging OPERATION button
 Private string GetPageBar (PagedDataSource PPS) {string pageBar = string. empty; // declare the page tag text int currentPageIndex = pds. currentPageIndex + 1; // obtain the index of the current page // determine the link page of the home page if (currentPageIndex = 1) // if this page is the first page, it indicates that it is the homepage {pageBar + = "Homepage";} else {// if it is not the homepage, the address of the homepage link will be 1 pageBar + = "// get the data source, relink data //////
 
  
DataTable, data source
 Private DataTable GetDataTable () {DataTable dt = new DataTable (); // create a database table using (SqlConnection con = new SqlConnection ("server = .; dataBase = MyBlog; uid = sa; pwd = 1; ") {con. open (); // Open the database link SqlCommand sqlCom = new SqlCommand (); // declare and create the database command set StringBuilder sqlStr = new StringBuilder (); // declare the SQL statement sqlStr. append ("select * from match"); // obtain the SQL statement sqlCom. commandText = sqlStr. toString (); // specify the SQL statement sqlCom FOR THE sqlcommand object. connection = con; // specify the link object SqlDataAdapter sqlDa = new SqlDataAdapter (sqlCom) for the sqlcommand object; // declare the database adapter SqlCommandBuilder sqlBuilder = new SqlCommandBuilder (sqlDa); sqlDa. fill (dt); // Fill the table} return dt ;}}}

Demo: Repeater tips.
Conclusion

 

This article mainly introduces the basic usage of the Repeater control, and uses two examples to learn more about the use of the Repeater control. Although the Repeater control has few encapsulated operations, it is the most basic data binding control. In addition, you can use other controls to make up for the shortcomings of the Repeater control, for example, you can use the PagedataSource class to implement data paging. This article is not over yet. The next article will focus on ListView.

 

 

 

 

 

 

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.