在一些网站上常看见如上图的效果,点击的改变颜色,换一个点击,原先的颜色恢复。
<asp:DataList ID="DataList1" runat="server" RepeatDirection="Horizontal" RepeatColumns="5" SelectedIndex="0">
<SelectedItemStyle BackColor="Fuchsia" />
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%#Eval("area") %>' CommandName="Select" OnClick="LinkButton1_Click">
<%#Eval("area") %>
</asp:LinkButton>
</ItemTemplate>
</asp:DataList>
1.设置LinkButton的CommandName属性为Select,如:
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Select" onclick="LinkButton1_Click"> <%#Eval("area")%> </asp:LinkButton>
2.在DataList1的SelectedIndexChanged事件中,将点中的行号赋值给ViewState["no"]
protected void DataList1_SelectedIndexChanged(object sender, EventArgs e) { ViewState["no"] = DataList1.SelectedIndex.ToString(); DataList1.DataBind(); }
3.DataList1的ItemDataBound事件中设置颜色
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e) { LinkButton linbtn = (LinkButton)e.Item.FindControl("LinkButton1"); linbtn.ForeColor = System.Drawing.Color.Blue; if (ViewState["no"] != null) { if (e.Item.ItemIndex == Convert.ToInt16(ViewState["no"])) linbtn.ForeColor = System.Drawing.Color.Red; } }