实现类似Windows资源管理器的DataGrid
2024-07-21 02:24:50
供稿:网友
在datagrid中,我们可以实现类似windows资源管理器的效果,即对列进行排序,该列颜色与其它列不同。下面就是实现的代码:
c#代码:
datagridlikewindowsexplorer.aspx
<%@ page language="c#" codebehind="datagridlikewindowsexplorer.aspx.cs"
autoeventwireup="false" inherits="aspxwebcs.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="javascript">
<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="javascript" 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
}
}