在DataGrid中,我们可以实现类似Windows资源管理器的效果,即对列进行排序,该列颜色与其它列不同。下面就是实现的代码:
C#代码:
DataGridLikeWindowsExplorer.ASPx
<%@ Page language="c#" Codebehind="DataGridLikeWindowsExplorer.aspx.cs"
AutoEventWireup="false" Inherits="aspx<a href="http://dev.21tx.com/web/" target="_blank">Web</a>CS.DataGridLikeWindowsExplorer" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>DataGridLikeWindowsExplorer</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="<a href="http://dev.21tx.com/web/javascript/" target="_blank">JavaScript</a>">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
<style type="text/css">
.gridtooltip {
BORDER-RIGHT: black 1px solid;
PADDING-RIGHT: 4px;
BORDER-TOP: black 1px solid;
PADDING-LEFT: 4px;
Z-INDEX: 200;
LEFT: 0px;
VISIBILITY: hidden;
PADDING-BOTTOM: 4px;
FONT: 9pt bold 宋体;
BORDER-LEFT: black 1px solid;
WIDTH: 150px;
COLOR: white;
PADDING-TOP: 4px;
BORDER-BOTTOM: black 1px solid;
POSITION: absolute;
TOP: 0px;
BACKGROUND-COLOR: #ff3316
}
</style>
<script language="<a href="http://dev.21tx.com/java/" target="_blank">Java</a>script" type="text/javascript">
function showheadertip(idx)
{
var tooltip
if (document.getElementById)
tooltip = document.getElementById('htip' + idx)
else
tooltip = eval("document.all['htip" + idx + "']");
if (tooltip != null)
{
tooltip.style.pixelLeft = event.clientX + 5;
tooltip.style.pixelTop = event.clientY + 5;
tooltip.style.visibility = "visible";
}
}
function hideheadertip(idx)
{
var tooltip
if (document.getElementById)
tooltip = document.getElementById('htip' + idx)
else
tooltip = eval("document.all['htip" + idx + "']");
if (tooltip != null)
{
tooltip.style.visibility = "hidden";
}
}
</script>
</HEAD>
<body MS_POSITIONING="GridLayout">
<asp:PlaceHolder ID="Tips_PlaceHolder" Runat="server"></asp:PlaceHolder>
<form id="DataGridLikeWindowsExplorer" method="post" runat="server">
<div align="center">
<h4>Northwind职员表</h4>
<asp:DataGrid ID="WinExplorerView_DataGrid" Runat="server" BorderColor="#FF6600"
BorderStyle="None" BorderWidth="5px" BackColor="White" CellPadding="5" AllowSorting="True"
AutoGenerateColumns="False" AllowPaging="True" GridLines="Horizontal" PageSize="5">
<SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#669999"></SelectedItemStyle>
<ItemStyle ForeColor="#000066"></ItemStyle>
<HeaderStyle Font-Bold="True" HorizontalAlign="Center" ForeColor="Navy" BackColor="#FFCC00"></HeaderStyle>
<FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
<Columns>
<asp:BoundColumn DataField="LastName" SortExpression="LastName" HeaderText="姓"></asp:BoundColumn>
<asp:BoundColumn DataField="FirstName" SortExpression="FirstName" HeaderText="名字"></asp:BoundColumn>
<asp:BoundColumn DataField="Title" SortExpression="Title" HeaderText="职位"></asp:BoundColumn>
<asp:BoundColumn DataField="BirthDate" SortExpression="BirthDate" HeaderText="出生日期"
DataFormatString="{0:d}"/></asp:BoundColumn>
<asp:BoundColumn DataField="City" SortExpression="City" HeaderText="居住地"></asp:BoundColumn>
</Columns>
<PagerStyle HorizontalAlign="Left" ForeColor="#000066" BackColor="White" Mode="NumericPages"></PagerStyle>
</asp:DataGrid>
</div>
</form>
</body>
</HTML>
DataGridLikeWindowsExplorer.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.Caching;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace aspxWebCS
{
/// <summary>
/// DataGridLikeWindowsExplorer 的摘要说明。
/// </summary>
public class DataGridLikeWindowsExplorer : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid WinExplorerView_DataGrid;
protected System.Data.SqlClient.SqlDataAdapter m_sqlDataAdapter;
protected System.Data.SqlClient.SqlCommand m_sqlSelectCommand;
protected System.Data.SqlClient.SqlConnection m_sqlConnection;
protected System.Data.DataSet m_dsEmployees;
protected System.Data.DataView m_dvEmployees;
protected System.Collections.Hashtable colHeaderMap;
protected string m_strSortExpr;
protected string m_strSortOrder;
protected int m_iSortColumnIdx;
protected System.Web.UI.WebControls.PlaceHolder Tips_PlaceHolder;
protected string strConn = "Data Source=.;User Id=sa;Password=;Initial Catalog=Northwind;";
private void Page_Load(object sender, System.EventArgs e)
{
m_iSortColumnIdx = -1;
m_strSortExpr = "";
m_strSortOrder = "";
ProcessViewState();
PrepareColumnHeaderMap();
if (!IsPostBack)
{
BindGridToView();
}
}
private void PrepareColumnHeaderMap()
{
colHeaderMap = new Hashtable();
int idx = 0;
foreach (DataGridColumn col in WinExplorerView_DataGrid.Columns)
{
colHeaderMap[col.SortExpression] = idx++;
}
}
private void RetrieveData()
{
if (null == Cache["EmployeesDS"])
{
string tmp = "SELECT LastName, FirstName, Title, BirthDate, City FROM Employees";
m_sqlConnection = new SqlConnection(strConn);
m_sqlSelectCommand = new SqlCommand(tmp, m_sqlConnection);
m_sqlDataAdapter = new SqlDataAdapter(m_sqlSelectCommand);
m_dsEmployees = new DataSet("Employees");
m_sqlDataAdapter.Fill(m_dsEmployees);
Cache.Insert("EmployeesDS", m_dsEmployees, null, DateTime.Now.AddMinutes(1), Cache.NoSlidingExpiration);
}
else
{
m_dsEmployees = (DataSet)Cache["EmployeesDS"];
}
}
private void ProcessViewState()
{
if (null != ViewState["SortExpr"])
{
m_strSortExpr = ViewState["SortExpr"].ToString();
}
if (null != ViewState["SortOrder"])
{
m_strSortOrder = ViewState["SortOrder"].ToString();
}
}
private void BindGridToView()
{
string strSort = "";
if (0 != m_strSortExpr.Length)
{
strSort = m_strSortExpr;
if (0 != m_strSortOrder.Length)
{
strSort += (" " + m_strSortOrder);
}
}
RetrieveData();
m_dvEmployees = new DataView(m_dsEmployees.Tables[0], "", strSort, DataViewRowState.CurrentRows);
WinExplorerView_DataGrid.DataSource = m_dvEmployees;
WinExplorerView_DataGrid.DataBind();
}
private Color GetSortColumnColor()
{
if (null == this.m_strSortOrder ||
String.Empty == this.m_strSortOrder||
0 == this.m_strSortOrder.Length)
{
return Color.Gold;
}
if (m_strSortOrder.CompareTo("ASC") == 0)
{
return Color.Gold;
}
else
{
return Color.BlanchedAlmond;
}
}
private void OnPageIndexChange(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
WinExplorerView_DataGrid.CurrentPageIndex = e.NewPageIndex;
BindGridToView();
}
private void OnSortView(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
m_strSortExpr = e.SortExpression;
ViewState["SortExpr"] = m_strSortExpr;
if (0 == m_strSortOrder.Length)
{
m_strSortOrder = "ASC";
}
else if (m_strSortOrder.CompareTo("ASC") == 0)
{
m_strSortOrder = "DESC";
}
else
{
m_strSortOrder = "ASC";
}
ViewState["SortOrder"] = m_strSortOrder;
// 找到Click事件所在的列序号
m_iSortColumnIdx = Convert.ToInt32(this.colHeaderMap[m_strSortExpr]);
BindGridToView();
}
private void OnItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
int idx = 0;
foreach (TableCell cl in e.Item.Cells)
{
cl.Attributes.Add("onmouseover", "showheadertip(" + idx.ToString() + ");");
cl.Attributes.Add("onmouseout", "hideheadertip(" + idx.ToString() + ");");
idx++;
}
}
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
if (-1 != m_iSortColumnIdx)
{
e.Item.Cells[m_iSortColumnIdx].BackColor = GetSortColumnColor();
}
}
}
protected override void OnPreRender(EventArgs e)
{
///ToolTip文字
int nCount = this.WinExplorerView_DataGrid.Columns.Count;
for (int i = 0; i < nCount; i++)
{
Panel pnl = new Panel();
pnl.CssClass = "gridtooltip";
pnl.ID = "htip" + i.ToString();
Literal lt = new Literal();
lt.Text = this.GetHeaderTooltipText(i);
pnl.Controls.Add(lt);
this.Tips_PlaceHolder.Controls.Add(pnl);
}
base.OnPreRender (e);
}
private string GetHeaderTooltipText(int iColIdx)
{
switch (iColIdx)
{
case 0:
return "职员的姓";
case 1:
return "职员名字";
case 2:
return "职员的职位";
case 3:
return "出生日期";
case 4:
return "居住地";
default:
throw new ArgumentException("无效地列序号", "Index");
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.WinExplorerView_DataGrid.ItemCreated +=
new System.Web.UI.WebControls.DataGridItemEventHandler(this.OnItemCreated);
this.WinExplorerView_DataGrid.PageIndexChanged +=
new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.OnPageIndexChange);
this.WinExplorerView_DataGrid.SortCommand +=
new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.OnSortView);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}