Who would like to use the lost technology if it weren't for work?
Introduction
Previous articles have talked about the content of AJAX, using AJAX technology to develop efficient website applications, but it is not enough to have only AJAX technology in the development of B/S projects. There are more things to learn when entering B/S, but compared with the complex logic structure of C/S, B/S is still very simple in development.
Data binding controls are often used in the development of B/S projects. NET platform has well encapsulated these controls. As long as a little experienced ape can use these data controls quickly, the next few articles will discuss data controls. First of all, the details of data controls will be discussed. On the basic usage of ListView, GridView, Repeater and DataList controls, and at the end of the series of articles after the conference, a comprehensive analysis and summary of these controls is made.
Repeater of Binding Controls
NET encapsulates a variety of data binding controls, such as GridView, DataList, etc. But this article will start with Repeater, because Repeater only provides basic data binding template, without other functions such as built-in paging, so it is the most original data binding control, as long as it can skillfully use other binding of Repeater control. Control is also very simple.
1. Introduction to Repeater
Repeater controls are basic templated data lists. It does not visualize design formats or styles like GridView controls, so all formats, formats, and style tags must be explicitly declared in the control template at development time. In addition, the Repeater control has no built-in functions such as selection, sorting, editing, paging, etc. It only provides basic data binding, but it provides developers with ItemCommand events, which support sending and receiving commands in the control.
Templates are essential to bind data. Repeater controls also support data templates. They can also add tags to templates. They are mainly used as follows:
Note: Each Repeater control must define ItemTemplate.
2. Control Use Skills
The basic use of Repeater and some of its basic features are explained above. Next, several classic examples are given to use Repeater control.
1. Delete and Edit Data Binding
This example will use Asp.net's foreground and background to display data, and can edit and delete data.
Delete the page:
Edit the page:
Front-end code: After clicking the edit button, it will enter the edit page. The page is controlled by two Panel controls. The ID number is passed to determine whether the page is edited or deleted. In addition, the front-end code transmits the ID number needed to be judged by setting the CommandArgument attribute of the control.
<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> <td><%#Eval("name") %></td> <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> <td><asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name") %>'></asp:TextBox></td> <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">To update</asp:LinkButton> </td> </tr> </asp:Panel> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </div> </form> </body>
Background Code: Two important events in the background code are ItemCommand and ItemDataBound, in which ItemCommand is responsible for receiving button commands from the front desk, setting the id passed by the back desk according to the parameters of the command, and verifying id judgment in ItemDataBound to 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 ID number of the specified row operation /// <summary> /// Binding data when forms are loaded /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { this.DataBindToRepeater();//Binding data to Repeater controls } } /// <summary> /// Binding data sources to Repeater controls /// </summary> private void DataBindToRepeater() { //Connecting database with using statement 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 = "select * from match"; //Specify execution statements for command objects sqlcom.Connection = sqlCon; //Specify connection objects for command objects this.userRepeat.DataSource = sqlcom.ExecuteReader(); //Specify a data source for the Repeater object this.userRepeat.DataBind(); //Binding data sources } } /// <summary> /// Repeater control command event /// </summary> /// <param name="source"></param> /// <param name="e"></param> protected void userRepeat_ItemCommand(object source, RepeaterCommandEventArgs e) { //Get the command text, determine what type of command is issued, and invoke events according to the command type if (e.CommandName=="Edit") //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 Line Content Command { id = int.Parse(e.CommandArgument.ToString()); //Get the ID number of deleted rows //Delete the selected row and re-specify the binding operation this.DeleteRepeater(id); } else if (e.CommandName == "Update") //Update Line Content Command { //Get the content and ID number of the updated row string strText = ((TextBox)e.Item.FindControl("txtName")).Text.Trim(); int intId=int.Parse(((Label)e.Item.FindControl("lblID")).Text); //Update the contents of Repeater controls this.UpdateRepeater(strText,intId); } //Rebind content on controls this.DataBindToRepeater(); } /// <summary> /// Delete line content /// </summary> /// <param name="intId"> Delete the ID </param> of the contents of the row 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"; //Specify execution statements for command objects sqlcom.Connection = sqlCon; //Specify connection objects for command objects //Create parameter sets and add parameter sets to sqlcom SqlParameter sqlParam = new SqlParameter("@id", intId); sqlcom.Parameters.Add(sqlParam); sqlcom.ExecuteNonQuery(); //Specify UPDATE statement } } /// <summary> /// Update the contents of the Repeater control /// </summary> /// <param name="strText">modified content </param> /// <param name="intId">ID number of the line 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 database connection SqlCommand sqlcom = new SqlCommand(); //Create database command object sqlcom.CommandText = "update match set name=@str where id=@id"; //Specify execution statements for command objects sqlcom.Connection = sqlCon; //Specify connection objects for command objects //Create parameter sets and add parameter sets to sqlcom SqlParameter[] sqlParam = { new SqlParameter("@str", strText), new SqlParameter("@id", intId) }; sqlcom.Parameters.AddRange(sqlParam); sqlcom.ExecuteNonQuery(); //Specify UPDATE statement } } /// <summary> /// Events occurring during data binding of Repeater control /// </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 and, if so, verify that editing has been done. //ListItemType enumerations represent different items in a list control that can include, for example, DataGrid, DataList, and Repeater controls. if (e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem) { //Obtain the bound data source. Note that the sqlReader method is used to bind the data source above, so the DbDataRecord method is used to obtain the data source below. //If the bound data source is of DataTable type, the following statement will cause an error. System.Data.Common.DbDataRecord record = (System.Data.Common.DbDataRecord)e.Item.DataItem; //Data source validation method of DataTable type //System.Data.DataRowView record = (DataRowView)e.Item.DataItem; //Determine whether the ID of the data source is equal to the current id, and if equal, prove that the click on the edit triggered 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; } } } } }
Paging - Page Data Source
Front-end code: Use the original html text and add a Literal tag to dynamically add and specify html tags.
Screenshot of the 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> </head> <body> <form id="form1" runat="server"> <div> <asp:Repeater ID="Repeater1" runat="server" > <HeaderTemplate> <table border="1" cellpadding="0" cellspacing="0" style="width:1006px;border-collapse:collapse; text-align:center;"> <tr> <th style="background-color:red">ID</th> <th style="background-color:red">content</th> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td><asp:Label ID="lblId" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"id") %>' ></asp:Label></td> <td><%# DataBinder.Eval(Container.DataItem,"name") %></td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </div> <div class="pageBar"> <asp:Literal ID="ltlPageBar" runat="server"></asp:Literal> </div> </form> </body> </html>
Background code: The data source of the Repeater control is the PagedDataSource object, which dynamically specifies the paging attributes for the object when the page is loaded, and uses Literal tags to dynamically specify the links for each tag to jump pages.
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 of the current page int pageIndex = 1; try { //Get the index number of the current requested jump page pageIndex = Convert.ToInt32(Request.QueryString["Page"]); //If it is page 0, it will jump to page 1. if (pageIndex <= 0) { pageIndex = 1; } } catch { pageIndex = 1; } DataTable dt = this.GetDataTable(); //Get the bound data table PagedDataSource pds = new PagedDataSource(); //Creating Paging Data Source Objects pds.DataSource = dt.DefaultView; //Setting up data sources for data source objects pds.AllowPaging = true; //Object Allow Paging pds.PageSize = 2; //Set the size of the object displayed per page pds.CurrentPageIndex = pageIndex - 1; //Set the current page of the data source //Binding Paging Data Source Control to Repeater Control this.Repeater1.DataSource = pds; this.Repeater1.DataBind(); //Use Literal tags to dynamically specify links to jump pages for each tag ltlPageBar.Text = this.GetPageBar(pds); } } /// <summary> /// Get the link address of the jump page on each label /// </summary> /// <param name="pds">paging data source object </param> /// html text of < returns > paging operation button </returns > private string GetPageBar(PagedDataSource pds) { string pageBar = string.Empty; //Declare page label text int currentPageIndex = pds.CurrentPageIndex + 1; //Get the current page index //Determine the Link Page on the Home Page if (currentPageIndex == 1) //If the page is the first page, prove that it is the first page. { pageBar += "<a href=\"javascript:void(0)\">home page</a>"; } else { //If it is not the home page, the address of the home page link will be 1 pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=1\">home page</a>"; } //Determine the address of the link on the previous page if ((currentPageIndex - 1) < 1) //If the previous page is less 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 link to the previous page. pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=" + (currentPageIndex - 1) + "\">Previous page</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 page. 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 on the last page 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 and re-link the data /// </summary> /// <returns>DataTable, data source </returns> private DataTable GetDataTable() { DataTable dt = new DataTable(); //Create database tables using (SqlConnection con = new SqlConnection("server=.;DataBase=MyBlog;uid=sa;pwd=1;")) { con.Open(); //Open database links SqlCommand sqlCom = new SqlCommand(); //Declare and create a database command set StringBuilder sqlStr = new StringBuilder(); //Declare sql statements sqlStr.Append("select * from match"); //Get sql statements sqlCom.CommandText = sqlStr.ToString(); //Specify sql statements for sqlcommand objects sqlCom.Connection = con; //Specify link objects for sqlcommand objects SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCom); //Declare the database adapter SqlCommandBuilder sqlBuilder = new SqlCommandBuilder(sqlDa); sqlDa.Fill(dt); //Fill table } return dt; } } }
Demo Download Address above: Repeater Skills.
http://files.cnblogs.com/files/netserver/Repeater.zip
Download address 2
epilogue
This paper mainly introduces the basic use of Repeater control, and through two examples to learn more about the use of Repeater control. Repeater control encapsulates fewer operations, but it is the most basic data binding control. In addition, it can make up for the deficiencies of Repeater control by using other controls, such as paging data by using PagedataSource class. This is not the end of the article. The next article will focus on ListView.