Detailed asp.net the use of repeater controls in data-binding operations _ practical Tips

Source: Internet
Author: User
Tags eval prev create database

Repeater of a bound control
. NET encapsulates a variety of data-bound controls, such as the GridView, DataList, and so on, but this article will start with Repeater, because repeater only provides basic data-binding templates, no built-in other paging, and so on, so it is the most original data-bound control, As long as you can skillfully use the repeater control of other bound controls is very simple.
1, Repeater introduction
The Repeater control is a list of basic templated data. It does not have a visual design format or style like the GridView control, so you must explicitly declare all formatting, formatting, and style tags in the control template at development time. In addition, the Repeater control does not have built-in selection, sorting, editing, paging, and so on, it provides only basic data binding, but it provides developers with a ItemCommand event that supports sending and receiving commands in the control.
To bind the data, the template is essential, the Repeater control also supports the data template, and you can add the desired label to the template, which uses the following figure:

Note: Each Repeater control must define a ItemTemplate.

Second, the use of control techniques
the basic usage of repeater and some of its basic features are described above, followed by a few classic examples to apply the Repeater control.
1, data binding Delete, edit
The example will use the ASP.net foreground and backend combination to display the data and to edit and delete the data.
To delete a page:

Edit page:

Foreground code: After clicking the Edit button will enter the editing page, the page is controlled by two panel controls, by passing the ID number of the way to determine whether the page is edited or deleted, and the foreground code by setting the control's CommandArgument property to pass the background need to determine the ID number.

<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> operations </th> </tr> </thead> </HeaderTemplate> <itemt emplate> <asp:panel id= "Plitem" runat= "Server" > <tr> <td><asp:lab El runat= "Server" id= "lblid" text= ' <% #Eval ("ID")%> ' ></asp:Label></td> <td><% #E Val ("name")%></td> <td> <asp:linkbutton id= "Lbtedit" commandname= "Edit" Com MAndargument= ' <% #Eval ("id")%> ' runat= ' server ' > Edit </asp:LinkButton> <asp:linkbutton id= ' LBT 
            Delete "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")%> ' >&lt ;/asp:label></td> <td><asp:textbox id= "txtname" runat= "server" text= ' <% #Eval (' name ')%&G t; ' ></asp:TextBox></td> <td> <asp:linkbutton id= "Lbtcancel" Commandname= " Cancel "commandargument= ' <% #Eval (" id ")%> ' runat= ' server ' > Cancel </asp:LinkButton> <asp:linkbu Tton 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& 

 Gt

Background code: The two events that are important in the background code are ItemCommand and ItemDataBound, where ItemCommand is responsible for receiving the button commands from the foreground, setting the ID of the background pass according to the parameters of the command. And in the ItemDataBound to verify the ID of the switch 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 specified row operation ID number///<summary>///form load-bound data///</summary>///<param name= "Sender" ></para 
      m>///<param name= "E" ></param> protected void Page_Load (object sender, EventArgs e) { if (! Page.IsPostBack) {this. Databindtorepeater ()//BIND data to Repeater control}///<summary>///bind data source to Repeater control///&L t;/summary> private void Databindtorepeater () {//Use-statement for database connection using (SqlConnection sqlcon=new S Qlconnection ("server=.; Database=myblog;uid=sa;pwd=1 ")) {Sqlcon.open ()//Open database connection SqlCommand sqlcom = new SqlCommand ()  ; 
    To create a database command object    Sqlcom.commandtext = "SELECT * from Match"; Specifies the execution statement sqlcom for the Command object. Connection = Sqlcon; Specifies the Connection object this.userRepeat.DataSource = sqlcom for the command object.  ExecuteReader (); Specifies the data source for the Repeater object This.userRepeat.DataBind (); Bound data Source}}///<summary>///Repeater control command Event///</summary>///<param na Me= "source" ></param>///<param name= "E" ></param> protected void Userrepeat_itemcommand (obj ECT source, RepeaterCommandEventArgs e) {//Get command text, judge what type of command is issued, invoke event if (e.commandname== "Edit") according to command type /edit command {id = Int.  Parse (E.commandargument.tostring ()); 
      Get the command ID number} else if (e.commandname== "Cancel")//Cancel update command {id =-1; else if (e.commandname== "delete")//Delete Row content command {id = Int.  Parse (E.commandargument.tostring ()); Gets the ID number of the deleted row//Deletes the selected row and assigns the binding action again. 
      Deleterepeater (ID); else if (E.commanDname = = "Update")//Update row content command {//Get update row content and ID number string strText = ((TextBox) E.item.findcontrol ("Txtn Ame ")). 
        Text.trim (); int Intid=int. Parse ((Label) E.item.findcontrol ("Lblid")). 
        Text); Update the contents of the Repeater control this. 
      Updaterepeater (Strtext,intid); }//rebind content on control this. 
    Databindtorepeater (); ///<summary>///Delete Row content///</summary>///<param name= "intId" > Delete the contents of the line Id</pa ram> private void Deleterepeater (int intId) {using (SqlConnection sqlcon = new SqlConnection ("server=.; Database=myblog;uid=sa;pwd=1 ")) {Sqlcon.open ()//Open database connection SqlCommand sqlcom = new SqlCommand ()  ; Create DATABASE Command Object sqlcom.commandtext = "Delete from match where id= @id"; Specifies the execution statement sqlcom for the Command object. Connection = Sqlcon; 
        Specify the connection object for the Command object//create a parameter collection and add a parameter set to the sqlcom SqlParameter sqlparam = new SqlParameter ("@id", intId); Sqlcom. Parameters.Add (SQLPAram); Sqlcom.  ExecuteNonQuery (); Specify UPDATE statements}}///<summary>///update content in repeater controls///</summary>///<par Am Name= "StrText" > Modified content </param>///<param name= "IntId" > contents of the row ID number </param> private void UPD Aterepeater (String Strtext,int intId) {using (SqlConnection sqlcon = new SqlConnection ("server=.; Database=myblog;uid=sa;pwd=1 ")) {Sqlcon.open ()//Open database connection SqlCommand sqlcom = new SqlCommand ()  ; Create DATABASE Command Object sqlcom.commandtext = "Update match set name= @str where id= @id"; Specifies the execution statement sqlcom for the Command object. Connection = Sqlcon; Specify a Connection object for the Command object//create a parameter collection and add a parameter set to the sqlcom sqlparameter[] Sqlparam = {new SqlParameter ("@str", StrText), 
        New SqlParameter ("@id", IntId)}; Sqlcom. 
 
        Parameters.addrange (Sqlparam); Sqlcom.  ExecuteNonQuery (); Specify UPDATE statements}}///<summary>///The events that occur when a data binding is repeater control///;/summary>///<param name= "sender" ></param>///<param name= "E" ></param> Protec Ted void Userrepeat_itemdatabound (object sender, RepeaterItemEventArgs e) {//Determine whether the data in the Repeater control is a bound data source, and if so, will  
      Verifies that an edit operation is performed//listitemtype enumerations represent different items that 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) {//Get the bound data source, note here 
        To bind the data source using the Sqlreader method, the following DbDataRecord method gets//If the bound data source is a DataTable type use the following statement to make an error. 
        System.Data.Common.DbDataRecord record = (System.Data.Common.DbDataRecord) e.Item.DataItem; 
 
        Data source validation methods for datatable types//system.data.datarowview record = (DataRowView) e.Item.DataItem; Determine if the ID of the data source equals the current ID, and if it is equal, then the edit triggers the Userrepeat_itemcommand event if (id = int) is clicked. 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, Paging--pagedatasource
Foreground code: Use the original HTML text and add a literal tag to dynamically add and specify HTML tags.
Screenshot of page:

 

Background code: The Repeater control's data source is a PagedDataSource object that dynamically assigns paging properties to the page when it loads, and uses the literal tag to dynamically specify the link for each label jump 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 index of current page int pageIndex = 1; 
          try {//Get the index number of the currently requested jump page PageIndex = Convert.ToInt32 (request.querystring["page")); 
          If page No. 0 will jump to page 1th if (pageIndex <= 0) {pageIndex = 1; 
        The catch {PageIndex = 1; The DataTable dt = this. Getdatatable ();  Gets the data table of the binding pageddatasource PDS = new PagedDataSource (); Create a paging data source object PDS. DataSource = dt.  DefaultView; Sets the data source PDS for the data source object. AllowPaging = true; Object allows paging of PDS.  PageSize = 2; Sets the size PDS that the object displays 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 = PDS; This. 
 
        Repeater1.databind (); Use the Literal tab to dynamically specify the link for each tab jump page Ltlpagebar.text = this. 
      Getpagebar (PDS); }///<summary>///gets the link address of the jump page on each label///</summary>///<param name= "PDS" > Points Page data source object </param>///<returns> Paging action button HTML text </returns> private string Getpagebar (PagedDataSource PDS) {String pagebar = string. Empty; Declare page label text int currentpageindex = PDS.  CurrentPageIndex + 1; Get the current page index//Judge the link page of the first page if (CurrentPageIndex = 1)////If the page is first, then prove it is homepage {pagebar + + <a hr 
      Ef=\ "javascript:void (0) \" > Home </a> "; else {//If not the first page, the address of the homepage link will be 1 Pagebar + + <a href=\ "" + Request.currentexecutionfilepa Th + "? Page=1\ "> Home &LT;/a> "; //Determine the address of the previous page link if ((currentPageIndex-1) < 1)//If the previous page is less than 1 then link to the first page {Pagebar + + <a hr 
      Ef=\ "javascript:void (0) \" > Prev </a> "; else {//If the previous page address is not 1 will link to the previous page Pagebar = "<a href=\" "+ Request.currentexecutionfilepat H + "? 
      Page= "+ (currentPageIndex-1) +" \ "> Prev </a>"; //Specify the link address for the next page if ((CurrentPageIndex + 1) > PDS. PageCount) {//If the address of the next page is greater than the total number of pages, it will be connected to the home Pagebar + + <a href=\ "javascript:void (0) \" > next page &LT;/A&G 
      t; ";} else {//otherwise link to next page Pagebar = "<a href=\" "+ Request.currentexecutionfilepath +"? 
      Page= "+ (CurrentPageIndex + 1) +" \ "> Next </a>"; ///Specifies the last link address if (CurrentPageIndex = PDS. 
      PageCount) {Pagebar + = "<a href=\" javascript:void (0) \ "> Last </a>"; else {Pagebar = "<a href=\" + Request.currEntexecutionfilepath + "? Page= "+ PDS. 
      PageCount + "\" > Last </a> "; return pagebar; return HTML text}///<summary>///get the data source, relink the data///</summary>///<returns>datat 
      Able, data source </returns> private DataTable Getdatatable () {DataTable dt = new DataTable ();//CREATE DATABASE table using (SqlConnection con = new SqlConnection ("server=.;D 
      atabase=myblog;uid=sa;pwd=1; ")) {con. Open ();  Open the database link SqlCommand sqlcom = new SqlCommand (); Declares and creates a database command set StringBuilder sqlstr = new StringBuilder ();  Declares the SQL statement sqlstr.append ("SELECT * from Match"); Gets the SQL statement sqlcom.commandtext = sqlstr.tostring ();  Specifies the SQL statement for the SqlCommand object sqlcom.connection = con; Specifies the link object for the SqlCommand object SqlDataAdapter sqlDa = new SqlDataAdapter (sqlcom); 
        Declares the database adapter SqlCommandBuilder sqlbuilder = new SqlCommandBuilder (sqlDa); Sqlda.fill (DT); Populate table} return DT; 
 } 
 
  } 
}

The

Epilogue
article mainly describes 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 encapsulates fewer operations, it is the most basic data-bound control and can be used to compensate for the deficiencies of the repeater control by using other controls, such as by using the Pagedatasource class to implement pagination of the data. The article is not finished here, and 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.