高亮-点击-显示





3.00/5 (4投票s)
高亮点击的行并在另一页显示所选行信息。
顶部的图显示了所选行的突出显示。底部的图在第二页上显示了所选行信息。
引言
当我们点击 DataGrid 中的任何地方时,该行将被突出显示,并且所选行信息将在另一页上显示。这种技术的一个小缺点是它会增加发送到浏览器的流的大小。它还会为每一行向视图状态添加信息。
实现
在本文中,我们只需要在数据绑定到控件时访问数据项,因此我们将使用 ItemDataBound
事件。为 DataGrid 中的行添加交替颜色相对容易。但是,当我们鼠标悬停在行上时,我们可能希望突出显示该行,并可能为所选行添加单击事件选项。现在让我们在进入代码之前创建一个表单。
<asp:datagrid id="DataGrid1"
OnItemDataBound="Item_Bound" AutoGenerateColumns="False"
CellPadding="2" SelectedItemStyle-BackColor="#33ccff"
BorderColor="#CC9966" BorderWidth="2px" EnableViewState="False"
Font-Size="12pt"
style="Z-INDEX: 101; LEFT: 100px; POSITION: absolute; TOP: 47px"
runat="server" >
<Columns>
<asp:BoundColumn DataField="LastName"
HeaderText="Last Name" ItemStyle-Width="150px">
</asp:BoundColumn>
<asp:BoundColumn DataField="FirstName"
HeaderText="First Name" ItemStyle-Width="150px">
</asp:BoundColumn>
<asp:BoundColumn DataField="Date"
HeaderText="_Date" ItemStyle-Width="150px">
</asp:BoundColumn>
<asp:ButtonColumn ButtonType="LinkButton"
CommandName="Select" Visible="False">
</asp:ButtonColumn>
</Columns>
</asp:datagrid>
请注意,我添加了一个 OnItemDataBound
函数,Item_Bound
。在 ASPX 中添加一个 JavaScript 函数。
<script language="javascript">
var lastColorUsed;
function DG_changeBackColor(row, highlight)
{
if (highlight)
{
row.style.cursor = "hand";
lastColorUsed = row.style.backgroundColor;
row.style.backgroundColor = '#87cefa';
}
else
row.style.backgroundColor = lastColorUsed;
}
</script>
这是实现目标的 Item_Bound
函数。
public void Item_Bound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
//Header color
if (e.Item.ItemType.ToString() == @"Header")
{
// Set background color.
e.Item.BackColor = System.Drawing.Color.LightGray;
}
if ((e.Item.ItemType == ListItemType.Pager) ||
(e.Item.ItemType == ListItemType.Header) ||
(e.Item.ItemType == ListItemType.Footer))
{
return;
}
else
{
e.Item.Attributes.Add("onmouseover",
"javascript:DG_changeBackColor(this, true);");
e.Item.Attributes.Add("onmouseout",
"javascript:DG_changeBackColor(this,false);");
//Pass the first name and last name to the "Test.axps".
string strLastName =
(string)DataBinder.Eval(e.Item.DataItem, "LastName");
string strFirstName =
(string)DataBinder.Eval(e.Item.DataItem, "FirstName");
//Highlight the selected row and display
//the information on the "Test.aspx" page.
e.Item.Attributes.Add("onclick",
"javascript:DG_changeBackColor(this,true);" +
"window.open('Test.aspx?LastName=" + strLastName +
"&FirstName=" + strFirstName +
"', 'popup', 'width=600, height=200, menubar=yes,
toolbar=yes, scrollbars=yes,
titlebar=yes, resizable=yes,status=yes,status=yes ')");
}
}
我希望指示用户单击了多少行,所以我没有取消突出显示先前单击的行。
结论
如您所见,突出显示一行并在另一页上显示所选行信息很容易。有不同的方法可以更改 DataGrid 中数据的输出和格式。您选择的方法取决于您想要执行的操作。
历史
- 2007年7月30日 -- 发布原始版本