日期:2014-05-18 浏览次数:20450 次
<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { DataList1.DataSource = new String[] { "A", "B", "C", "D", "E", "F", "G", "H" }; DataList1.DataBind(); } protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e) { //只有加判断,下面的代码才不会出错 if (e.Item.ItemType == ListItemType.Header) { CheckBox CheckBox1 = e.Item.FindControl("CheckBox1") as CheckBox; CheckBox1.Checked = true; } //要改变内容,需要e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem //不加判断,是会出错的, //也可以使用if(e.Item.ItemIndex >-1)进行判断 if (e.Item.ItemType == ListItemType.Item) { Label x = e.Item.FindControl("x") as Label; x.Text = "修改过的内容"; } } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:DataList ID="DataList1" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" RepeatLayout="Flow" OnItemDataBound="DataList1_ItemDataBound"> <HeaderTemplate> <asp:CheckBox ID="CheckBox1" runat="server" /> </HeaderTemplate> <ItemTemplate> <div style="background-color: Silver"> <asp:Label ID="x" runat="server" Text="Label1"></asp:Label> <%#Container.DataItem%></div> </ItemTemplate> <AlternatingItemTemplate> <div style="background-color: Green"> <asp:Label ID="x" runat="server" Text="Label1"></asp:Label> <%#Container.DataItem%></div> </AlternatingItemTemplate> </asp:DataList> </form> </body> </html>