当你在看repeater控件的时候相信你已经有相当的基础了,但是我们还是先来看看repeater的基本的知识吧。
Repeater没有默认外观,它完全使用模板来控制。这些模板实质包括各种模板元素中列出的HTML代码片段和.NET服务器控件。Repeater这类模板控件使用绑定表达式绑定数据,格式:<%# Eval("字段")%>
例:
头部
<HeaderTemplate>
<TABLE border="1"><TR><TD>用户名</TD><TD>年龄</TD></TR>
</HeaderTemplate>
重复项
<ItemTemplate>
<TR>
<TD><%# ((DataRowView)Container.DataItem)["username"] %></TD>
<TD><%# ((DataRowView)Container.DataItem)["age"] %></TD>
</TR>
</ItemTemplate>
尾部
<FooterTemplate>
</TABLE>
</FooterTemplate>
C#部分:private void Page_Load(object sender, System.EventArgs e)
{
// 创建数据集
DataSet ds = new DataSet();
// 添加表格
DataTable tbl = ds.Tables.Add("mytable");
// 添加字段
tbl.Columns.Add("username");
tbl.Columns.Add("age", typeof(int));
// 添加新行
DataRow row = tbl.NewRow();
row["username"] = "小王";
row["age"] = 28;
tbl.Rows.Add(row);
row = tbl.NewRow();
row["username"] = "小郭";
row["age"] = 27;
tbl.Rows.Add(row);
// 给Repeater控件设置数据源并进行数据绑定
Repeater1.DataSource = tbl.DefaultView; // ds.Tables[0].DefaultView;
Repeater1.DataBind();
}
下面给出一个小妹最近做的一个系统的部分有关于repeater的内容,希望对大家有所帮助:
前台的代码如下:(为了清晰和对初学者一个全面的帮助,给出全部的代码)大牛绕道
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MgMsgBoard.aspx.cs" Inherits="CompanyManage_MgMsgBoard"
ValidateRequest="false" EnableEventValidation="false" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
<link href="../css/Msg_Board.css" rel="stylesheet" type="text/css" />
<link href="css/option0.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.hidden
{
width: 490px;
margin-left: 100px;
border-style: solid;
border-width: 10px;
border-color: #FFFFE1;
}
.LinkReply
{
float: right;
margin-right: 50px;
cursor: pointer;
}
</style>
<script type="text/javascript" language="javascript">
function Hidden()
{
var Str=lWord.style.display;
if(Str=="none"){
lWord.style.display="inline";
}
else if(Str=="inline"){
lWord.style.display="none";
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td valign="top" height="25">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="td5" nowrap>
</td>
<td class="td2" id="viewinfo" style="cursor: pointer" onclick="my('viewinfo','hint');"
align="center" nowrap>
查看/回复留言<%=rMsg %>
</td>
<td class="td8" nowrap>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td valign="top" height="27">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td height="27" class="td4" nowrap>
<span id="hint" class="td7"><strong>查看/回复留言</strong></span>
</td>
<td class="td6" nowrap>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td height="27">
</td>
</tr>
</table>
<asp:Repeater ID="Repeater_Msg_Board" runat="server" OnItemDataBound="Repeater_Msg_Board_ItemDataBound">
<HeaderTemplate>
<div class="wrap">
<!--<table width="960" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="tableTop" onclick="Hidden();">
留下您的宝贵建议吧
</td>
</tr>
</table>
<div id="words" style="width: 970px; display: inline;">
<iframe id="Iframe1" runat="server" src="CompanyManage/lWords.aspx" frameborder="0"
width="970px" height="260px"></iframe>
</div>
-->
</HeaderTemplate>
<ItemTemplate>
<div class="message">
<div class="Title">
<div class="head_img">
<a href="/lgq_0714">
<img src="../images/Msg_tipic.png" alt="lgq_0714" height="75" width="75" /></a>
</div>
<div class="message_title">
<ul>
<li><span class="user">楼主:<%#((DataRowView)Container.DataItem)["UserName"]%></span>
<span class="tpic">
<%#((DataRowView)Container.DataItem)["LeaveTime"]%>留言</span> <span class="LinkReply">
<!--<asp:HyperLink ID="Reply" runat="server" Text="回复"></asp:HyperLink>-->
</span>
<li>
<%#((DataRowView)Container.DataItem)["Message"]%></li>
<!--<li style="display:none"><asp:Label ID="MBID" runat="server" Text='<%#((DataRowView)Container.DataItem)["ID"]%>'></asp:Label></li>-->
</ul>
</div>
</div>
<div class="clear">
</div>
<asp:Repeater ID="Repeater_Msg_Reply" runat="server" DataSource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myreleation") %>'>
<ItemTemplate>
<div class="reply">
<div class="reply_img">
<a href="/yinyuan1987">
<img src="../images/Msg_rply.jpg" alt="yinyuan1987" height="50px" width="50px" /></a>
</div>
<div class="message_reply">
<ul>
<li><span class="user">
<%#((DataRow)Container.DataItem)["rUserName"]%>
</span><span class="tpic">
<%#((DataRow)Container.DataItem)["rLeaveTime"]%>回复</span></li>
<li>
<%#((DataRow)Container.DataItem)["rMessage"]%></li>
</ul>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
<div class="hidden" id="lWord">
<div>
<asp:TextBox ID="rMessage" runat="server" TextMode="MultiLine" Width="100%" Height="50px" BorderColor="#E4F4FC" BorderStyle="Solid" BorderWidth="2px"></asp:TextBox>
</div>
<div>
<asp:Button ID="bReply" CommandArgument='<%#((DataRowView)Container.DataItem)["ID"]%>'
runat="server" Text="回 复" OnClick="bReply_Click" />
</div>
</div>
</div>
</ItemTemplate>
<FooterTemplate>
</div>
<table width="100%">
<tr>
<td style="font-size: 12pt; color: #0099ff; background-color: #e6feda; text-align: right;
padding-right: 30px;">
共<asp:Label ID="lblpc" runat="server" Text="Label"></asp:Label>页 当前为第
<asp:Label ID="lblp" runat="server" Text="Label"></asp:Label>页
<asp:HyperLink ID="hlfir" runat="server" Text="首页"></asp:HyperLink>
<asp:HyperLink ID="hlp" runat="server" Text="上一页"></asp:HyperLink>
<asp:HyperLink ID="hln" runat="server" Text="下一页"></asp:HyperLink>
<asp:HyperLink ID="hlla" runat="server" Text="尾页"></asp:HyperLink>
跳至第
<asp:DropDownList ID="ddlp" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlp_SelectedIndexChanged">
</asp:DropDownList>
页
</td>
</tr>
<tr>
<td style="height: 1px; width: 100%;">
</td>
</table>
<hr style="color: #FD5800; height: 1px; width: 100%" />
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>
后台代码如下:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DataSetExclusiveNewsTableAdapters;
using System.Data.SqlClient;
public partial class CompanyManage_MgMsgBoard : System.Web.UI.Page
{
protected int Msg_CmpId;
protected string rMsg;//显示的是回复的内容
protected string Admin;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Companyusername"].ToString() == null)
{
Response.Write("<script language='javascript'>alert('非法操作,请先登录!');location.href = 'CompanyLogin.aspx';</script>");
}
else
{
Admin = Session["Companyusername"].ToString();
var id = new T_ExclusiveTableAdapter().SelectIdByAdmin(Admin);
Msg_CmpId = Convert.ToInt32(id);
if (Msg_CmpId == 0)
{
Response.Write("<script language='javascript'>alert('没有该单位的信息。');location.href='CompanyLogin.aspx';</script>");
}
else if (!IsPostBack)
{
this.Repeater_Msg_Board.DataSource = bindData();
this.Repeater_Msg_Board.DataBind();
}
}
}
//数据绑定
protected PagedDataSource bindData()
{
string connStr = ConfigurationManager.ConnectionStrings["WebSetConnectionString"].ConnectionString;
DataSet ds = new DataSet();
//连接数据库
SqlConnection conn = new SqlConnection(connStr);
//获取主表中的数据插入DataSet中去
SqlDataAdapter dap = new SqlDataAdapter("select * from T_MessageBoard where CompanyId=" + Msg_CmpId + "order by LeaveTime desc", conn);
dap.Fill(ds, "MB");
SqlDataAdapter dap1 = new SqlDataAdapter("select * from T_Reply order by rLeaveTime asc", conn);
dap1.Fill(ds, "Reply");
DataRelation l_relation = new DataRelation("myreleation", ds.Tables["MB"].Columns["ID"], ds.Tables["Reply"].Columns["MBID"], false);
ds.Relations.Add(l_relation);
PagedDataSource pds = new PagedDataSource();
pds.DataSource = ds.Tables["MB"].DefaultView;
pds.AllowPaging = true;
pds.PageSize = 5;
pds.CurrentPageIndex = Convert.ToInt32(Request.QueryString["page"]);
return pds;
}
//查找在repeater中的数据控件并实现分页和得到回复内容
protected void Repeater_Msg_Board_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
/*/TextBox r = (TextBox)Repeater_Msg_Board.FindControl("rMessage");
//rMsg = r.Text;
//查找Item
if (e.Item.ItemType == ListItemType.Item)
{
//TextBox rMessage = (TextBox)e.Item.FindControl("rMessage");
//rMsg = rMessage.Text ;
//((TextBox)e.Item.FindControl("rMessage")).Text="nihaowshi";
}
*/
//查找Footer内容,实现分页
if (e.Item.ItemType == ListItemType.Footer)
{
DropDownList ddlp = (DropDownList)e.Item.FindControl("ddlp");
HyperLink lpfirst = (HyperLink)e.Item.FindControl("hlfir");
HyperLink lpprev = (HyperLink)e.Item.FindControl("hlp");
HyperLink lpnext = (HyperLink)e.Item.FindControl("hln");
HyperLink lplast = (HyperLink)e.Item.FindControl("hlla");
bindData().CurrentPageIndex = ddlp.SelectedIndex;
int n = Convert.ToInt32(bindData().PageCount);//n为分页总数
int i = Convert.ToInt32(bindData().CurrentPageIndex);//i为当前页
Label lblpc = (Label)e.Item.FindControl("lblpc");
lblpc.Text = n.ToString();
Label lblp = (Label)e.Item.FindControl("lblp");
lblp.Text = Convert.ToString(bindData().CurrentPageIndex + 1);
if (!IsPostBack)
{
for (int j = 0; j < n; j++)
{
ddlp.Items.Add(Convert.ToString(j + 1));
}
}
if (i <= 0)
{
lpfirst.Enabled = false;
lpprev.Enabled = false;
lplast.Enabled = true;
lpnext.Enabled = true;
}
else
{
lpprev.NavigateUrl = "?id=" + Msg_CmpId + "&page=" + (i - 1);
}
if (i >= n - 1)
{
lpfirst.Enabled = true;
lplast.Enabled = false;
lpnext.Enabled = false;
lpprev.Enabled = true;
}
else
{
lpnext.NavigateUrl = "?id=" + Msg_CmpId + "&page=" + (i + 1);
}
lpfirst.NavigateUrl = "?id=" + Msg_CmpId + "&page=0";//向本页传递数据page
lplast.NavigateUrl = "?id=" + Msg_CmpId + "&page=" + (n - 1);
ddlp.SelectedIndex = Convert.ToInt32(bindData().CurrentPageIndex);//更新下拉列表框中的当前选中页序号
}
}
//在进行分页显示
protected void ddlp_SelectedIndexChanged(object sender, EventArgs e)
{
//脚模板中的下拉列表框更改时激发
int pg = Convert.ToInt32(((DropDownList)sender).SelectedValue) - 1;//获取列表框当前选中项
Response.Redirect("Msg_Board.aspx?id=" + Msg_CmpId + "&page=" + pg);//页面转向
}
//点击子repeater按钮回复
protected void bReply_Click(object sender, EventArgs e)
{
//找到留言主题的ID号
Button bReply = (Button)sender;
///////////////////////////////////////////
//得到了,该行的index的值也就是需要的索引值
int n = ((RepeaterItem)bReply.Parent).ItemIndex;
//////////////////////////////////////////
int MBID = Convert.ToInt32(bReply.CommandArgument.ToString());
//得到rMessage的值
TextBox r = (TextBox)Repeater_Msg_Board.Items[n].FindControl("rMessage");
rMsg = r.Text;
//得到留言的时间
DateTime dt = System.DateTime.Now;
int an = 1;//非匿名
//得到回复的内容不能为空
string testrMsg = rMsg;
if (testrMsg.Trim() == "")
{
Response.Write("<script language=javascript>alert('回复不能为空');location.href='MgMsgBoard.aspx'</script>");
}
else
{
string connStr = ConfigurationManager.ConnectionStrings["WebSetConnectionString"].ConnectionString;
SqlConnection sql = new SqlConnection(connStr);
sql.Open();
SqlCommand cmd = sql.CreateCommand();
cmd.CommandText = "insert into T_Reply(MBID,rUserName,rMessage,rLeaveTime,rAnonymity) values(@id,@User,@Ms,@LT,@An)";
cmd.Parameters.Add(new SqlParameter("id",MBID));
cmd.Parameters.Add(new SqlParameter("User",Admin));
cmd.Parameters.Add(new SqlParameter("Ms",rMsg));
cmd.Parameters.Add(new SqlParameter("LT",dt));
cmd.Parameters.Add(new SqlParameter("An",an));
cmd.ExecuteNonQuery();
sql.Close();
Response.Write("<script language='javascript'>alert('回复成功!');location.href='MgMsgBoard.aspx';</script>");
}
}
}
<span style="font-size:18px;color:#ff0000;">以上为全部的代码,当然还有些的其他的东西,就不给出来了,着已经是最大的贡献了,代码中不明白的地方请详细看代码,或者联系本人:欢迎QQ交流:1174632606或者关注微信公众号:FreshManIT 留言。</span>