Visual Studio .NET 2002.NET 1.0IISVisual Studio .NET 2003WebForms.NET 1.1高级开发Visual StudioWindows.NETASP.NETC#
启用 DataList 行高亮和单击事件回发
使用非显示按钮和数据绑定技术启用 DataList 行高亮和点击事件回发。
引言
在关于 优化 DataGrid 排序 的文章中,我们介绍了非显示按钮以及如何使用它来触发回发事件。 在本文中,我们将演示如何使用非显示按钮和一些高级数据绑定技术来启用 ASP.NET DataList
行高亮和行点击事件响应。
实现
使用 DHTML 和 JavaScript 实现表格行高亮并不难。 但是,为了实现传递表格行点击事件以及可识别的信息,我们必须使用动态数据绑定。 ASPX 代码如下
<asp:DataList ID="testDL" Runat="server">
<HeaderTemplate>
<table style="border-collapse:collapse; " border="1" cellpadding="4"
cellspacing="0" rules="rows"
width="100%">
<thead bgcolor="#0066ff" style="FONT-WEIGHT: bold; COLOR: white">
<td>First Name</td>
<td>Last Name</td>
<td>Address</td>
<td>Region</td>
<td>City</td>
<td>Postal Code</td>
<td>Country</td>
</thead>
</HeaderTemplate>
<ItemTemplate>
<tr <%# TRJavaScript(Container) %> >
<td><asp:Button
style="display:none;"
CommandArgument='<%# DataBinder.Eval(Container.DataItem,"EmployeeID")%>'
ID="HiddenButton" Runat="server" Text="View">
</asp:Button>
<%# DataBinder.Eval(Container.DataItem,"FirstName") %></td>
<td><%# DataBinder.Eval(Container.DataItem,"LastName") %></td>
<td><%# DataBinder.Eval(Container.DataItem,"Address") %></td>
<td><%# DataBinder.Eval(Container.DataItem,"Region") %></td>
<td><%# DataBinder.Eval(Container.DataItem,"City") %></td>
<td><%# DataBinder.Eval(Container.DataItem,"PostalCode") %></td>
<td><%# DataBinder.Eval(Container.DataItem,"Country") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>
非显示按钮与 DataList
中的普通按钮类似。 棘手的部分是 <%# TRJavaScript(Container) %>
。 在 DataList
项目模板中,Container
是 DataListItem
类型,并且每个 DataListItem
都是一个 Control
。 在这里,我们将 HiddenButton
的 ClientID
绑定到行 OnClick
事件响应代码。 bSwitch
、color1
和 color2
是类成员,它们有助于实现交替行背景。 行高亮颜色为黄色。
private bool bSwitch = false;
string color1 = "#ffffcc";
string color2 = "#ccff99";
public string TRJavaScript(Control con)
{
string tmp;
DataListItem dli = con as DataListItem;
Button btn = dli.FindControl("HiddenButton") as Button;
string _js = "bgcolor={0} onMouseover='rowcolor=this" +
".style.backgroundColor;this.style.backgroundColor" +
"=\"yellow\"; this.style.cursor = \"hand\"' " +
"onMouseout='this.style.backgroundColor=rowcolor;' " +
" onclick='document.getElementById(\"{1}\").click();' ";
tmp = bSwitch? string.Format(_js,color1, btn.ClientID) :
string.Format(_js,color2, btn.ClientID);
bSwitch = !bSwitch;
return tmp;
}
DataList
ItemCommand
事件响应与平常一样。 在这里,我们显示员工 ID。 请注意,我们使用 MS SQL NorthWind 数据库及其 employee 表。
private void testDL_ItemCommand(object source, DataListCommandEventArgs e)
{
this.lblID.Text = "This employee's ID is " + e.CommandArgument.ToString();
}