Repeater控件应用详解
1 在App_Data文件夹下建立一个数据库文件.mdf,创建一张新表,往里面灌一些数据;
2 新建一个DAL文件夹,添加数据集文件DataSet,利用强类型Dataset实现数据与页面的分离;
3 拖一个ObjectDataSource控件,选择数据源;
4 拽一个Repeater控件,选择数据源,排班;
切换到后台.aspx代码
1 <asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1"
2 onitemdatabound="Repeater1_ItemDataBound"
3 onitemcommand="Repeater1_ItemCommand">
4 <HeaderTemplate><table><tr><td>用户名</td><td>状态</td><td>操作</td></tr></HeaderTemplate>
5 <ItemTemplate>
6 <tr runat="server" id="trRow">
7 <td><%#Eval("UserName") %></td>
8 <td><%#Eval("Status") %></td>
9 <td>
10 <asp:Button runat="server" ID="btnEnabled" CommandName="Enabled" CommandArgument='<%#Eval("Id") %>' Text="启用" />
11 <asp:Button runat="server" ID="btnDisabled" CommandName="Disabled" CommandArgument='<%#Eval("Id") %>' Text="禁用" OnClientClick="return confirm('真的要禁用吗?')" />
12 </td>
13 </tr>
14 </ItemTemplate>
15 <FooterTemplate></table></FooterTemplate>
16 </asp:Repeater>
5 Repeater有ItemDataBound和ItemCommand事件;
1 protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
2 {
3 //只处理Item类型,对于Header等类型则不处理
4 if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
5 {//没有给AlternatingItem,但是偶数行也是e.Item.ItemType=AlternatingItem
6 DataRowView rowView = (DataRowView)e.Item.DataItem;
7 var userRow = (ASP.NET高级.DAL.DataSetUsers.T_UsersRow)rowView.Row;
8 if (userRow.Status == "禁用")
9 {
10 //1 把这行高亮显示
11 HtmlTableRow trRow = (HtmlTableRow)e.Item.FindControl("trRow");
12 trRow.Attributes["class"] = "disabledRow";
13
14 Button btnEnabled = (Button)e.Item.FindControl("btnEnabled");
15 Button btnDisabled = (Button)e.Item.FindControl("btnDisabled");
16
17 //2 显示启用按钮
18 btnEnabled.Visible = true;
19 //3 不显示禁用按钮
20 btnDisabled.Visible = false;
21 }
22 else if (userRow.Status == "启用")
23 {
24 //1 把这行普通显示
25 HtmlTableRow trRow = (HtmlTableRow)e.Item.FindControl("trRow");
26 trRow.Attributes["class"] = "";//空的
27
28 Button btnEnabled = (Button)e.Item.FindControl("btnEnabled");
29 Button btnDisabled = (Button)e.Item.FindControl("btnDisabled");
30
31 //2 不显示启用按钮
32 btnEnabled.Visible = false;
33 //3 显示禁用按钮
34 btnDisabled.Visible = true;
35
36 }
37 else//写严谨的程序,可以尽早的发现问题
38 {
39 throw new Exception("非法的status状态");
40 }
41 }
42
43 }
44
45 protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
46 {
47 if (e.CommandName=="Enabled")//启用
48 {
49 long id = Convert.ToInt64(e.CommandArgument);
50 T_UsersTableAdapter adapter = new T_UsersTableAdapter();
51 adapter.EnableUserById(id);
52 Repeater1.DataBind();//Don't forget!!!
53 }
54 else if (e.CommandName=="Disabled")//禁用
55 {
56 long id = Convert.ToInt64(e.CommandArgument);
57 T_UsersTableAdapter adapter = new T_UsersTableAdapter();
58 adapter.DisableUserById(id);
59 Repeater1.DataBind();//Don't forget!!!
60 }
61 }
Over. . .