asp.net中Repeater控件用法笔记

作者:袖梨 2022-06-25

大家可能都对datagrid比较熟悉,但是如果在数据量大的时候,我们就得考虑使用repeater作为我们的数据绑定控件了。Repeater控件与DataGrid (以及DataList)控件的主要区别是在于如何处理HTML。ASP.NET建立HTML代码以显示DataGrid控件,但Repeater允许开发人员决定如何显示数据。所以,你可以选择将数据显示在一个HTML表格中或者一个顺序列表中。这主要取决于你的选择,但你必须将正确的HTML插入到 ASP.NET页面中。
   模板与DataList一样,Repeater控件只支持模板。以下的模板可供选择:
  AlternatingItemTemplate: 指定如何显示每一其它选项。
  ItemTemplate: 指定如何显示选项。(AlternatingItemTemplate可以覆盖这一模板。)
   HeaderTemplate: 建立如何显示标题。
  FooterTemplate: 建立如何显示页脚。
  SeparatorTemplate: 指定如何显示不同选项之间的分隔符。
  你可以使用这些模板来显示你希望的数据。唯一具有强制性的模板是ItemTemplate,所有其它的模板都是具有选择性的。
  对于处理一个数据源,Repeater控件具有与DataGrid与DataList相同的属性:
 
  DataMember:获得或者设置与 Repeater 控件绑定的相应DataSource属性的表格。
 
  DataSource:获得或者设置为 Repeater 显示提供数据的数据源。
 
  除此之外,还有一个Items属性,你可以通过这一属性编程访问Repeater数据中单一选项。它返回一个RepeaterItemCollection对象,为一组RepeaterItem对象的集合,代表 Repeater 数据的每一行。
 
  ASP.NET Web数据控件还有其它一个共性:它们都使用DataBind方法来生成用户界面。调用这一方法可以返回并显示数据(假设DataSource和 DataMember属性设置正确)。在查看DataBind方法之前,我们先看看如何在一个Web页面中使用一个Repeater控件。
      使用Repeater控件
  使用Repeater控件的第一步骤是决定我们将要使用的数据源和字段。例如,我们将要使用SQL Server Northwind数据库中的Employees列表。Web页面将显示职工的完整名字,地址,以及电话号码。HTML将使用DIV标记,用 Repeater 模板来分隔内容。下面是 Web 页面的 HTML 内容:


前台代码

 代码如下 复制代码


               


                   
                       
                       
                       
                       
                       
                   
                 
               
                   

                       
                       
                       
                       
                       
                   
               
               
编号姓名年龄班级零花
<%#Eval("id")%><%#Eval("name")%><%#Eval("age")%><%#Eval("classid")%><%#Eval("salary")%>

           

后台代码

  

 代码如下 复制代码
  string sql = string.Format("select * from person");
        DataTable dt = sqlhelper.helper.ExecuteQuery(sql);
        Repeater1.DataSource = dt;
        Repeater1.DataBind();

AspNetpager的使用方法:

    首先注册<%@ Register Assembly="AspNetPager" Namespace="Wuqi.Webdiyer" TagPrefix="webdiyer" %>

前台:

  

 代码如下 复制代码
                  FirstPageText="首页" LastPageText="尾页" LayoutType="Table" NextPageText="下一页"
                onpagechanging="AspNetPager1_PageChanging" PageIndexBoxType="DropDownList"
                PagingButtonLayoutType="Span" PrevPageText="上一页" ShowCustomInfoSection="Left"
                ShowPageIndexBox="Always" SubmitButtonText="Go" TextAfterPageIndexBox="页"
                TextBeforePageIndexBox="转到" Width="450px" PageSize="3">
               

后台:

  

 代码如下 复制代码
  private void AddPages(Repeater rpt,Wuqi.Webdiyer.AspNetPager anp,DataTable dt)
        {
            PagedDataSource pds = new PagedDataSource();
            pds.AllowPaging = true;
            pds.DataSource = dt.DefaultView;
    
            anp.RecordCount = dt.Rows.Count;//给分页控件指定当前总数
            pds.PageSize = anp.PageSize;//确定分页,每页有n项
            pds.CurrentPageIndex = anp.CurrentPageIndex - 1;//确定当前页数
    
            rpt.DataSource = pds;//绑定数据源
            rpt.DataBind();
        }
        protected void AspNetPager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
        {
            AspNetPager1.CurrentPageIndex = e.NewPageIndex;
            BindPersonData();
        }


例子

repeater控件动态添加、删除一行

 代码如下 复制代码

Repeater:

 代码如下 复制代码



           
               
                   
                       
                       
                       
                       
                       
                       
                   
               
               
                                        onitemdatabound="rptRequest_ItemDataBound">
                       
                           

                               
                               
                               
                               
                               
                               
                               
                           
                       
                   
               
           
序号明细编号
                            资产类型
                       

                            使用工位
                       

                            申请数量
                       

                            发放的资产号(资产管理员填写)
                       

                                    <%# Container.ItemIndex+1 %>
                                   
                               

                                   
                                   
                               

                                   
                                   
                               

                                    

后台:

 代码如下 复制代码

///


        /// 绑定repeater的数据源
        ///

        private void RepeaterBindData()
        {
            DataTable dt = DefineDataTableSchema(hfRptColumns.Value);
            if (Request["BusinessNo"] == null)
            {
                LoadData(dt);
            }
            else
            {
                LoadData(Request["BusinessNo"].ToString(), dt);
            }

            rptRequest.DataSource = dt;
            rptRequest.DataBind();
        }


        private void LoadData(string businessNo, DataTable dt)
        {
            string strSql = "select * from EMS_EquipmentRequestItem where BussinessNo = '"+ businessNo +"'";
            DataTable dt_EquipmentRequestItem = DBUtility.DbHelperSQL.Query(strSql).Tables[0];

            //for (int i = 0; i < dt_EquipmentRequestItem.Rows.Count; i++)
            foreach (DataRow dr in dt_EquipmentRequestItem.Rows)
            {
                DataRow row = dt.NewRow();
                row["Guid"] = Guid.NewGuid();
                row["EquRequestItemId"] = dr["EquRequestItemId"].ToString();
                row["EquipmentType"] = dr["TypeId"].ToString();
                row["Station"] = dr["StationId"].ToString();
                row["EquipmentNum"] = dr["EquipmentNum"].ToString();
                row["EquipmentIds"] = dr["EquipmentIds"].ToString();
                dt.Rows.Add(row);
            }
        }


        ///


        /// repeater数据默认加载
        ///

        ///
        private void LoadData(DataTable dt)
        {
            //默认显示1行
            for (int i = 0; i < 1; i++)
            {
                DataRow row = dt.NewRow();
                dt.Rows.Add(row);
            }

            //为第一行加载一些数据
            DataRow row0 = dt.Rows[0];
            row0["Guid"] = Guid.NewGuid();
            row0["EquRequestItemId"] = "";
            row0["EquipmentType"] = "";
            row0["Station"] = "";
            row0["EquipmentNum"] = "1";//默认初始为1
            row0["EquipmentIds"] = "";
        }

        ///


        /// 根据repeater相对应的列名,定义数据源datatable的schema
        ///

        /// 列名
        ///
        public DataTable DefineDataTableSchema(string columns)
        {
            DataTable dt = new DataTable();
            string[] columnsAry = columns.Split(',');
            foreach (string str in columnsAry)
            {
                dt.Columns.Add(str);
            }
            return dt;
        }

        protected void rptRequest_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "add")
            {
                System.Web.UI.WebControls.Label lblGuid = (System.Web.UI.WebControls.Label)e.Item.FindControl("lblGuid");

                //首先,恢复数据源
                DataTable dt = DefineDataTableSchema(hfRptColumns.Value);
                foreach (RepeaterItem item in rptRequest.Items)
                {
                    DataRow newRow = dt.NewRow();
                    newRow["Guid"] = ((System.Web.UI.WebControls.Label)item.FindControl("lblGuid")).Text;
                    newRow["EquRequestItemId"] = ((System.Web.UI.WebControls.Label)item.FindControl("lblEquRequestItemId")).Text;
                    newRow["EquipmentType"] = ((DropDownList)item.FindControl("ddlEquipmentType")).SelectedValue;
                    newRow["Station"] = ((DropDownList)item.FindControl("ddlStation")).SelectedValue;
                    newRow["EquipmentNum"] = ((TextBox)item.FindControl("txtReqEquipmentNum")).Text;
                    newRow["EquipmentIds"] = ((TextBox)item.FindControl("txtEquipmentIds")).Text;
                    dt.Rows.Add(newRow);

                    if (lblGuid.Text == ((System.Web.UI.WebControls.Label)item.FindControl("lblGuid")).Text)
                    {
                        //添加一行
                        DataRow row = dt.NewRow();
                        row["Guid"] = Guid.NewGuid();
                        row["EquipmentType"] = "";
                        row["Station"] = "";
                        row["EquipmentNum"] = "1";//默认初始为1
                        row["EquipmentIds"] = "";
                        dt.Rows.Add(row);
                    }
                }

                rptRequest.DataSource = dt;
                rptRequest.DataBind();
            }
            else if (e.CommandName == "delete")
            {
                System.Web.UI.WebControls.Label lblGuid = (System.Web.UI.WebControls.Label)e.Item.FindControl("lblGuid");

                //首先,恢复数据源
                DataTable dt = DefineDataTableSchema(hfRptColumns.Value);
                foreach (RepeaterItem item in rptRequest.Items)
                {
                    if (lblGuid.Text != ((System.Web.UI.WebControls.Label)item.FindControl("lblGuid")).Text)
                    {
                        DataRow newRow = dt.NewRow();
                        newRow["Guid"] = ((System.Web.UI.WebControls.Label)item.FindControl("lblGuid")).Text;
                        newRow["EquRequestItemId"] = ((System.Web.UI.WebControls.Label)item.FindControl("lblEquRequestItemId")).Text;
                        newRow["EquipmentType"] = ((DropDownList)item.FindControl("ddlEquipmentType")).SelectedValue;
                        newRow["Station"] = ((DropDownList)item.FindControl("ddlStation")).SelectedValue;
                        newRow["EquipmentNum"] = ((TextBox)item.FindControl("txtReqEquipmentNum")).Text;
                        newRow["EquipmentIds"] = ((TextBox)item.FindControl("txtEquipmentIds")).Text;
                        dt.Rows.Add(newRow);
                    }
                }

                rptRequest.DataSource = dt;
                rptRequest.DataBind();
            }
        }

        protected void rptRequest_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DropDownList ddlEquipmentType_temp = e.Item.FindControl("ddlEquipmentType") as DropDownList;

                string sqlstr = @"select distinct b.TypeId,b.EquipmentName + '_' + b.EquipmentType as 'EquipmentName_EquipmentType'
                                from EMS_EquipmentInfo a
                                join EMS_EquipmentType b on a.TypeId = b.TypeId and b.Status = '1'
                                order by EquipmentName_EquipmentType";
                DataSet ds = DBUtility.DbHelperSQL.Query(sqlstr);
                ddlEquipmentType_temp.DataTextField = "EquipmentName_EquipmentType";
                ddlEquipmentType_temp.DataValueField = "TypeId";
                ddlEquipmentType_temp.DataSource = ds;
                ddlEquipmentType_temp.DataBind();
                ddlEquipmentType_temp.SelectedValue = (e.Item.FindControl("lblEquipmentType") as System.Web.UI.WebControls.Label).Text;


                DropDownList ddlStation_temp = e.Item.FindControl("ddlStation") as DropDownList;

                string sqlstr2 = @"select NodeId,Line + '_' + StationName as 'Line_StationName' from V_Stations where status='1' order by Line_StationName";
                DataSet ds2 = DBUtility.DbHelperSQL.Query(sqlstr2);
                ddlStation_temp.DataTextField = "Line_StationName";
                ddlStation_temp.DataValueField = "NodeId";
                ddlStation_temp.DataSource = ds2;
                ddlStation_temp.DataBind();
                ddlStation_temp.SelectedValue = (e.Item.FindControl("lblStation") as System.Web.UI.WebControls.Label).Text;


                TextBox txtEquIds = e.Item.FindControl("txtEquipmentIds") as TextBox;
                txtEquIds.Attributes.Add("readonly", "true");
              
                if (Request["BusinessNo"] != null)
                {
                    (e.Item.FindControl("btnAddRow") as System.Web.UI.WebControls.Button).Visible = false;
                    (e.Item.FindControl("btnDeleteRow") as System.Web.UI.WebControls.Button).Visible = false;

                    string businessNo = Request["BusinessNo"].ToString();
                    bool IsApplyUser = Is_ApplyUser(Session["currentUserID"].ToString(), businessNo, "EMS_EquipmentRequest", "Requester");//是否为申请人本人
                    if (IsApplyUser == true)
                    {
                        string requestStatus = HttpUtility.UrlDecode(Request["RequestStatus"].ToString(), System.Text.Encoding.UTF8);//申请单的当前状态
                        if (requestStatus == "草稿" || requestStatus == "退回")
                        {
                            (e.Item.FindControl("btnAddRow") as System.Web.UI.WebControls.Button).Visible = true;
                            (e.Item.FindControl("btnDeleteRow") as System.Web.UI.WebControls.Button).Visible = true;
                        }
                    }
                    else
                    {
                        bool IsCurrentAppprovaler = Is_CurrentAppprovaler(Session["currentUserID"].ToString(), businessNo);//是否为当前能做审批的人
                        if (IsCurrentAppprovaler == true)
                        {
                            string sql = " SELECT TOP 1 LayerName from EMS_Approvaler where BussinessNo='" + businessNo + "' "
                                        + " AND ApprovalStatus='N' ORDER BY AppSequence ";
                            DataTable dt = DBUtility.DbHelperSQL.Query(sql).Tables[0];

                            if (dt.Rows.Count != 0 && dt.Rows[0]["LayerName"].ToString() == "资产管理员")
                            {
                                string ReqNum = (e.Item.FindControl("txtReqEquipmentNum") as TextBox).Text.Trim();
                                txtEquIds.Attributes.Add("onclick", "OpenWindow('" + txtEquIds.ClientID + "','" + ddlEquipmentType_temp.SelectedValue + "','" + ReqNum + "')");
                            }
                        }
                    }
 
                }

            }
        }

相关文章

精彩推荐