当前位置: 移动技术网 > IT编程>开发语言>.net > 详解ASP.NET数据绑定操作中Repeater控件的用法

详解ASP.NET数据绑定操作中Repeater控件的用法

2017年12月12日  | 移动技术网IT编程  | 我要评论

一路向西bt下载,克洛伊-马菲亚,全国生猪价格

2016617184159990.png (461×410)

一、绑定控件之repeater
.net封装了多种数据绑定控件,诸如gridview、datalist等但该篇文章将会从repeater入手,因为repeater只提供了基本的数据绑定模板,没有内置其它分页等功能,所以它是最原始的数据绑定控件,只要能够熟练运用repeater控件其它的绑定控件也就很简单了。
1、repeater简介
repeater 控件是基本模板化数据列表。 它不像gridview控件一样能够可视化的设计格式或样式,因此开发时在控件模板中必须显式声明所有格式、格式和样式标记。另外repeater控件没有内置选择、排序、编辑、分页等功能,它只提供了基本的数据绑定,但是它为开发人员提供了itemcommand 事件,该事件支持在控件中收发命令。
想要绑定数据,模板是必不可少的,repeater控件同样支持数据模板,而且还可以在模板中添加想要的标签,它主要用法如下图:

2016617184226837.png (554×365)

note:每个 repeater 控件必须定义 itemtemplate。

2016617184244624.png (870×204)

二、控件使用技巧
上文讲解了repeater基本的使用方法及它的一些基本特性,接下来做几个经典的示例来运用repeater控件。
1、数据绑定之删除、编辑
该示例将会使用asp.net的前台和后台结合来实现显示数据,并能够编辑和删除数据。
删除页面:

2016617184314017.png (1006×152)

编辑页面:

2016617184335193.png (1007×163)

前台代码:在单击编辑按钮后将会进入编辑页面,页面是由两个panel控件来控制,通过传递id号的方式判断显示的是编辑页面还是删除页面,另外前台代码通过设置控件的commandargument属性来传递后台所需要判断的id号。

<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>内容</th> 
              <th>操作</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">编辑</asp:linkbutton> 
              <asp:linkbutton id="lbtdelete" commandname="delete" commandargument='<%#eval("id") %>' runat="server">删除</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">取消</asp:linkbutton> 
              <asp:linkbutton id="lbtupdate" commandname="update" commandargument='<%#eval("id") %>' runat="server">更新</asp:linkbutton> 
            </td> 
          </tr> 
        </asp:panel> 
      </itemtemplate> 
      <footertemplate> 
        </table> 
      </footertemplate> 
    </asp:repeater> 
  </div> 
  </form> 
</body> 

后台代码:在后台代码中很重要的两个事件是itemcommand和itemdatabound,其中itemcommand负责接收前台传进来的按钮命令,根据命令的参数来设置后台传递的id,并在itemdatabound中来验证id判断切换显示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; //保存指定行操作所在的id号 
    /// <summary> 
    /// 窗体加载时绑定数据 
    /// </summary> 
    /// <param name="sender"></param> 
    /// <param name="e"></param> 
    protected void page_load(object sender, eventargs e) 
    { 
      if (!page.ispostback) 
      { 
        this.databindtorepeater();//将数据绑定到repeater控件上 
      } 
    } 
 
    /// <summary> 
    /// 将数据源绑定repeater控件上 
    /// </summary> 
    private void databindtorepeater() { 
      //使用using语句进行数据库连接 
      using (sqlconnection sqlcon=new sqlconnection("server=.;database=myblog;uid=sa;pwd=1")) 
      { 
        sqlcon.open(); //打开数据库连接 
 
        sqlcommand sqlcom = new sqlcommand();  //创建数据库命令对象 
        sqlcom.commandtext = "select * from match"; //为命令对象指定执行语句 
        sqlcom.connection = sqlcon; //为命令对象指定连接对象 
 
        this.userrepeat.datasource = sqlcom.executereader();  //为repeater对象指定数据源 
        this.userrepeat.databind(); //绑定数据源 
      } 
    } 
 
    /// <summary> 
    /// repeater控件命令事件 
    /// </summary> 
    /// <param name="source"></param> 
    /// <param name="e"></param> 
    protected void userrepeat_itemcommand(object source, repeatercommandeventargs e) 
    { 
      //获取命令文本,判断发出的命令为何种类型,根据命令类型调用事件 
      if (e.commandname=="edit") //编辑命令 
      { 
        id = int.parse(e.commandargument.tostring());  //获取命令id号 
      } 
      else if (e.commandname=="cancel")  //取消更新命令 
      { 
        id = -1; 
      } 
      else if(e.commandname=="delete")  //删除行内容命令 
      { 
        id = int.parse(e.commandargument.tostring());  //获取删除行的id号 
        //删除选定的行,并重新指定绑定操作 
        this.deleterepeater(id); 
      } 
      else if (e.commandname == "update") //更新行内容命令 
      { 
        //获取更新行的内容和id号 
        string strtext = ((textbox)e.item.findcontrol("txtname")).text.trim(); 
        int intid=int.parse(((label)e.item.findcontrol("lblid")).text); 
        //更新repeater控件的内容 
        this.updaterepeater(strtext,intid); 
      } 
 
      //重新绑定控件上的内容 
      this.databindtorepeater(); 
    } 
 
    /// <summary> 
    /// 删除行内容 
    /// </summary> 
    /// <param name="intid">删除行所在内容的id</param> 
    private void deleterepeater(int intid) { 
      using (sqlconnection sqlcon = new sqlconnection("server=.;database=myblog;uid=sa;pwd=1")) 
      { 
        sqlcon.open(); //打开数据库连接 
 
        sqlcommand sqlcom = new sqlcommand();  //创建数据库命令对象 
        sqlcom.commandtext = "delete from match where id=@id"; //为命令对象指定执行语句 
        sqlcom.connection = sqlcon; //为命令对象指定连接对象 
 
        //创建参数集合,并向sqlcom中添加参数集合 
        sqlparameter sqlparam = new sqlparameter("@id", intid); 
        sqlcom.parameters.add(sqlparam); 
 
        sqlcom.executenonquery();  //指定更新语句 
 
      } 
    } 
 
    /// <summary> 
    /// 更新repeater控件中的内容 
    /// </summary> 
    /// <param name="strtext">修改后的内容</param> 
    /// <param name="intid">内容所在行的id号</param> 
    private void updaterepeater(string strtext,int intid) { 
      using (sqlconnection sqlcon = new sqlconnection("server=.;database=myblog;uid=sa;pwd=1")) 
      { 
        sqlcon.open(); //打开数据库连接 
 
        sqlcommand sqlcom = new sqlcommand();  //创建数据库命令对象 
        sqlcom.commandtext = "update match set name=@str where id=@id"; //为命令对象指定执行语句 
        sqlcom.connection = sqlcon; //为命令对象指定连接对象 
 
        //创建参数集合,并向sqlcom中添加参数集合 
        sqlparameter[] sqlparam = { new sqlparameter("@str", strtext), new sqlparameter("@id", intid) }; 
        sqlcom.parameters.addrange(sqlparam); 
 
        sqlcom.executenonquery();  //指定更新语句 
         
      } 
    } 
 
    /// <summary> 
    /// repeater控件数据绑定时发生的事件 
    /// </summary> 
    /// <param name="sender"></param> 
    /// <param name="e"></param> 
    protected void userrepeat_itemdatabound(object sender, repeateritemeventargs e) 
    { 
      //判断repeater控件中的数据是否是绑定的数据源,如果是的话将会验证是否进行了编辑操作 
      //listitemtype 枚举表示在一个列表控件可以包括,例如 datagrid、 datalist和 repeater 控件的不同项目。  
      if (e.item.itemtype==listitemtype.item || e.item.itemtype==listitemtype.alternatingitem) 
      { 
        //获取绑定的数据源,这里要注意上面使用sqlreader的方法来绑定数据源,所以下面使用的dbdatarecord方法获取的 
        //如果绑定数据源是datatable类型的使用下面的语句就会报错. 
        system.data.common.dbdatarecord record = (system.data.common.dbdatarecord)e.item.dataitem; 
        //datatable类型的数据源验证方式 
        //system.data.datarowview record = (datarowview)e.item.dataitem; 
 
        //判断数据源的id是否等于现在的id,如果相等的话证明现点击了编辑触发了userrepeat_itemcommand事件 
        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
前台代码:使用原始的html文本,并添加了一个literal标签,用来动态添加并指定html标签。
页面截图:

2016617184644312.png (1016×99)

<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">内容</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> 

后台代码:repeater控件的数据源是pageddatasource对象,在页面加载时为该对象动态指定了分页的属性,并使用literal标签来动态指定每个标签跳转页的链接。

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) 
      { 
        //设置当前页的索引 
        int pageindex = 1; 
        try 
        { 
          //获取当前索要跳转页的索引号 
          pageindex = convert.toint32(request.querystring["page"]); 
          //如果是第0页将会跳转入第1页 
          if (pageindex <= 0) 
          { 
            pageindex = 1; 
          } 
        } 
        catch 
        { 
          pageindex = 1; 
        } 
 
        datatable dt = this.getdatatable(); //获取绑定的数据表 
 
        pageddatasource pds = new pageddatasource();  //创建分页数据源对象         
        pds.datasource = dt.defaultview;  //为数据源对象设置数据源 
        pds.allowpaging = true; //对象允许分页 
        pds.pagesize = 2;  //设置对象每页显示的大小 
        pds.currentpageindex = pageindex - 1; //设置数据源的当前页 
 
        //向repeater控件上绑定分页数据源控件 
        this.repeater1.datasource = pds; 
        this.repeater1.databind(); 
 
        //使用literal标签来动态指定每个标签跳转页的链接 
        ltlpagebar.text = this.getpagebar(pds); 
      } 
    } 
 
    /// <summary> 
    /// 获取每个标签上的跳转页的链接地址 
    /// </summary> 
    /// <param name="pds">分页数据源对象</param> 
    /// <returns>分页操作按钮的html文本</returns> 
    private string getpagebar(pageddatasource pds) 
    { 
      string pagebar = string.empty; //声明页面标签文本 
      int currentpageindex = pds.currentpageindex + 1;  //获取当前页索引 
 
      //判断首页的链接页面 
      if (currentpageindex == 1) //如果该页为第一页,则证明它为首页 
      { 
        pagebar += "<a href=\"javascript:void(0)\">首页</a>"; 
      } 
      else  
      { 
        //如果不是首页,首页链接的地址将会为1 
        pagebar += "<a href=\"" + request.currentexecutionfilepath + "?page=1\">首页</a>"; 
      } 
 
      //判断上一页链接的地址 
      if ((currentpageindex - 1) < 1) //如果上一页小于1则链接到第一页 
      { 
        pagebar += "<a href=\"javascript:void(0)\">上一页</a>"; 
      } 
      else 
      { 
        //如果上一页地址不是1将会链接到上一页 
        pagebar += "<a href=\"" + request.currentexecutionfilepath + "?page=" + (currentpageindex - 1) + "\">上一页</a>"; 
      } 
 
      //指定下一页的链接地址 
      if ((currentpageindex + 1) > pds.pagecount) 
      { 
        //如果下一页的地址大于总页数,将会连接到首页 
        pagebar += "<a href=\"javascript:void(0)\">下一页</a>"; 
      } 
      else 
      { 
        //否则的话链接到下一页 
        pagebar += "<a href=\"" + request.currentexecutionfilepath + "?page=" + (currentpageindex + 1) + "\">下一页</a>"; 
      } 
 
      //指定末页的链接地址 
      if (currentpageindex == pds.pagecount) 
      { 
        pagebar += "<a href=\"javascript:void(0)\">末页</a>"; 
      } 
      else 
      { 
        pagebar += "<a href=\"" + request.currentexecutionfilepath + "?page=" + pds.pagecount + "\">末页</a>"; 
      } 
 
      return pagebar; //返回html文本 
    } 
 
    /// <summary> 
    /// 获取数据源,重新链接数据 
    /// </summary> 
    /// <returns>datatable,数据源</returns> 
    private datatable getdatatable() 
    { 
      datatable dt = new datatable(); //创建数据库表 
      using (sqlconnection con = new sqlconnection("server=.;database=myblog;uid=sa;pwd=1;")) 
      { 
 
        con.open(); //打开数据库链接 
 
        sqlcommand sqlcom = new sqlcommand();  //声明并创建数据库命令集 
        stringbuilder sqlstr = new stringbuilder(); //声明sql语句 
        sqlstr.append("select * from match");  //获取sql语句 
 
        sqlcom.commandtext = sqlstr.tostring(); //为sqlcommand对象指定sql语句 
 
        sqlcom.connection = con;  //为sqlcommand对象指定链接对象 
        sqldataadapter sqlda = new sqldataadapter(sqlcom); //声明数据库适配器 
        sqlcommandbuilder sqlbuilder = new sqlcommandbuilder(sqlda); 
        sqlda.fill(dt); //填充表 
      } 
 
      return dt; 
    } 
 
  } 
} 

结语
文章主要介绍了repeater控件的基本使用方法,并通过两个示例来更深一步的学习了repeater控件的使用。虽然repeater控件封装的操作较少,但它是最基础的数据绑定控件,另外可以通过使用其它控件来弥补repeater控件的不足,如可以通过使用pagedatasource类来实现数据的分页。文章写到这里并没有结束,下篇文章将会着重讨论listview。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网