Describes how to use the Repeater control in ASP. NET data binding, asp. netrepeater
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.
<Body> <form id = "form1" runat = "server"> <div> <asp: repeater ID = "userRepeat" runat = "server" OnItemCommand = "userRepeat_ItemCommand" OnItemDataBound = "userRepeat_ItemDataBound"> <HeaderTemplate> <table border = "1" style = "width: 1000px; text-align: center; border-collapse: collapse; "> <thead style =" background-color: red; "> <tr> <th> ID </th> <th> content </th> <th> operation </th> </tr> </thead> </HeaderTemplate> <ItemTemplate> <asp: panel ID = "plItem" runat = "server"> <tr> <td> <asp: label runat = "server" ID = "lblID" Text = '<% # Eval ("id") %>'> </asp: label> </td> <% # Eval ("name") %> </td> <asp: linkButton ID = "lbtEdit" CommandName = "Edit" CommandArgument = '<% # Eval ("id") %> 'runat = "server"> Edit </asp: linkButton> <asp: LinkButton ID = "lbtDelete" CommandName = "Delete" CommandArgument = '<% # Eval ("id ") %> 'runat = "server"> Delete </asp: LinkButton> </td> </tr> </asp: Panel> <asp: panel ID = "plEdit" runat = "server"> <tr> <td> <asp: label runat = "server" ID = "Label1" Text = '<% # Eval ("id") %>'> </asp: label> </td> <asp: TextBox ID = "txtName" runat = "server" Text = '<% # Eval ("name ") %> '> </asp: TextBox> </td> <asp: linkButton ID = "lbtCancel" CommandName = "Cancel" CommandArgument = '<% # Eval ("id") %> 'runat = "server"> Cancel </asp: linkButton> <asp: LinkButton ID = "lbtUpdate" CommandName = "Update" CommandArgument = '<% # Eval ("id ") %> 'runat = "server"> Update </asp: LinkButton> </td> </tr> </asp: panel> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp: Repeater> </div> </form> </body>
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 /// <summary> /// bind data when the form is loaded /// </summary> /// <param name = "sender"> </param> // <param name = "e"> </param> protected Void Page_Load (object sender, EventArgs e) {if (! Page. isPostBack) {this. dataBindToRepeater (); // bind data to the Repeater control }}/// <summary> // bind the data source to the Repeater control /// </summary> private void DataBindToRepeater () {// use the using statement to connect the database to 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"; // specify the SQL statement for the command object Com. 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 }/// <summary> // Repeater control command event // </summary> /// <param name = "source"> </param >/// <param name = "e"> </param> 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 = "Ed It ") // 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 ")). te Xt. 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 ();} /// <summary> /// Delete the row content /// </summary> /// <param name = "intId"> Delete the ID of the row content </param> 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 }}/// <summary> // update the content in the Repeater control /// </summary> /// <param name = "strTex T "> modified content </param> // <param name =" intId "> ID of the row where the content is located </param> 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 a Connection for the command object Object // create a parameter set and add SqlParameter [] sqlParam = {new SqlParameter ("@ str", strText), new SqlParameter ("@ id ", intId)}; sqlcom. parameters. addRange (sqlParam); sqlcom. executeNonQuery (); // specify the update statement }}/// <summary> // event that occurs when the Repeater control is bound to data /// </summary> /// <param name = "sender"> </param> // <param name = "e"> </param> protected void userRepeat_ItemDataBound (object sender, repeaterItemEventArgs e ){ // Determine whether the data in the Repeater control is a bound data source. If yes, it will verify whether the edit operation is performed. // ListItemType enumeration indicates that the data can be included in a list control, for example, different projects of 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:
<Html xmlns =" http://www.w3.org/1999/xhtml "> <Head runat =" server "> <meta http-equiv =" Content-Type "content =" text/html; charset = UTF-8 "/> <title> </title> <style type =" text/css ">. pageBar {margin-top: 10px ;}. pageBar a {color: #333; font-size: 12px; margin-right: 10px; padding: 4px; border: 1px solid # ccc; text-decoration: none ;} </style>
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. P AgeSize = 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 );}} /// <summary> /// obtain the link address of the jump page on each tag /// </summary> /// <param name = "PPS"> paging data source object </param> // <returns> html text of the paging OPERATION button </returns> 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 turns out to be the homepage {pageBar + = "<a href = \" javascript: void (0) \ "> homepage </a> ";} else {// if it is not the homepage, the URL of the homepage will be 1 pageBar + = "<a href = \" "+ Request. currentExecutionFilePath + "? Page = 1 \ "> homepage </a>" ;}// determine the URL of the previous Page if (currentPageIndex-1) <1) // if the previous page is smaller than 1, link to the first page {pageBar + = "<a href = \" javascript: void (0) \ "> previous page </a> ";} else {// if the previous page address is not 1, it will be linked to the previous page pageBar + = "<a href = \" "+ Request. currentExecutionFilePath + "? Page = "+ (currentPageIndex-1) +" \ "> previous Page </a>";} // specify the URL of the next Page if (currentPageIndex + 1)> pds. pageCount) {// if the address on the next page is greater than the total number of pages, it will be connected to the homepage pageBar + = "<a href = \" javascript: void (0) \ "> next page </a>";} else {// otherwise, link to the next page pageBar + = "<a href = \" "+ Request. currentExecutionFilePath + "? Page = "+ (currentPageIndex + 1) +" \ "> next Page </a>";} // specify the link address of the last Page if (currentPageIndex = tp. pageCount) {pageBar + = "<a href = \" javascript: void (0) \ "> last page </a> ";} else {pageBar + = "<a href = \" "+ Request. currentExecutionFilePath + "? Page = "+ PPS. pageCount + "\"> last page </a> ";} return pageBar; // return html text} // <summary> // obtain the data source, relink data /// </summary> /// <returns> DataTable, data source </returns> private DataTable GetDataTable () {DataTable dt = new DataTable (); // create the 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 ;}}}
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.