讓Asp.NET的DataGrid可排序、可選擇、可分頁
2024-07-10 12:58:03
供稿:網(wǎng)友
 
datagrid是asp.net中的一個(gè)重要的控件,經(jīng)常我們都將datagrid做成可分頁的和可排序的,有時(shí)還需要加上選擇功能。這些都是經(jīng)常需要用到的方法,其實(shí)是比較簡(jiǎn)單的。
設(shè)計(jì)思路:
為了方便起見,我們連接sql server 2000的northwind數(shù)據(jù)庫的orders表,從數(shù)據(jù)庫里得到此表的數(shù)據(jù)視圖。利用datagrid的sortcommand事件實(shí)現(xiàn)排序。用一個(gè)模板列加上checkbox控件實(shí)現(xiàn)選擇。可用datagrid的屬性生成器的“分頁”選項(xiàng)或者自己修改html實(shí)現(xiàn)分頁。
html:
添加一個(gè)datagrid,命名為dgorder。
添加了一個(gè)模板列,模板列里放一個(gè)名為cb的checkbox控件。此列用來實(shí)現(xiàn)選擇
為要排序的每個(gè)列加上排序表達(dá)式sortexpression。
利用列的dataformatstring來格式化列,象dataformatstring="{0:d}"顯示日期格式。
設(shè)置pagesize="15"每頁顯示15行數(shù)據(jù),allowpaging="true" 為允許分頁 。
整個(gè)html頁代碼:
<form id="form1" method="post" runat="server">
<asp:datagrid id="dgorder" runat="server" height="515px" width="718px" autogeneratecolumns="false" allowsorting="true" cellpadding="4" borderwidth="1px" bordercolor="#a0abeb" pagesize="15" borderstyle="solid" backcolor="white" gridlines="vertical" forecolor="black" allowpaging="true" showfooter="true">
<selecteditemstyle forecolor="white" backcolor="black"></selecteditemstyle>
<alternatingitemstyle backcolor="#eeeeee"></alternatingitemstyle>
<headerstyle horizontalalign="center" forecolor="white" bordercolor="#6876c5" backcolor="#6876c5"></headerstyle>
<footerstyle forecolor="white" backcolor="#6876c5"></footerstyle>
<columns>
<asp:templatecolumn>
<itemtemplate>
<font face="">
<asp:checkbox id="cb" runat="server"></asp:checkbox></font>
</itemtemplate>
</asp:templatecolumn>
<asp:boundcolumn datafield="orderid" sortexpression="orderid" headertext="id">
<headerstyle width="180px"></headerstyle>
</asp:boundcolumn>
<asp:boundcolumn datafield="shipcountry" sortexpression="shipcountry" headertext="shipcountry">
<headerstyle width="180px"></headerstyle>
</asp:boundcolumn>
<asp:boundcolumn datafield="shippeddate" sortexpression="shippeddate" headertext="shippeddate" dataformatstring="{0:d}">
<headerstyle width="180px"></headerstyle>
</asp:boundcolumn>
<asp:boundcolumn datafield="freight" sortexpression="freight" headertext="freight">
<headerstyle width="180px"></headerstyle>
</asp:boundcolumn>
<asp:boundcolumn datafield="shipaddress" sortexpression="shipaddress" headertext="shipaddress">
<headerstyle width="480px"></headerstyle>
</asp:boundcolumn>
</columns>
<pagerstyle horizontalalign="center" forecolor="black" position="topandbottom" backcolor="white" mode="numericpages"></pagerstyle>
</asp:datagrid>
</form>
后臺(tái)代碼:
'得到數(shù)據(jù)視圖,參數(shù)為要排序的列
private function getdv(byval strsort as string) as dataview
 '定義數(shù)據(jù)庫連接
 dim dv as dataview
 dim cn as new sqlconnection()
 try
 '初始化連接字符串
 cn.connectionstring = "data source=pmserver;
 initial catalog=northwind;persist security info=false;user id=sa;password=sa;"
 cn.open()
'從northwind得到orders表的數(shù)據(jù)
 dim adp as sqldataadapter = new sqldataadapter("select * from orders", cn)
 dim ds as new dataset()
 adp.fill(ds)
 '得到數(shù)據(jù)視圖
 dv = ds.tables(0).defaultview
 catch ex as exception
#if debug then
 session("error") = ex.tostring()
 response.redirect("../error.aspx") '跳轉(zhuǎn)程序的公共錯(cuò)誤處理頁面
#end if
 finally
 '關(guān)閉連接
 cn.close()
 end try
 '排序
 dv.sort = strsort
 return dv
 end function
 private sub page_load(byval sender as system.object, byval e as system.eventargs) 
 handles mybase.load
 if not ispostback then
 viewstate("strsort") = "orderid"
 dgorder.datasource = getdv(viewstate("strsort").tostring())
 dgorder.databind()
 end if
 end sub
'排序
 private sub dgorder_sortcommand(byval source as object, 
 byval e as system.web.ui.webcontrols.datagridsortcommandeventargs) handles dgorder.sortcommand
 dgorder.currentpageindex = 0
 '得到排序的列
 viewstate("strsort") = e.sortexpression.tostring()
 dgorder.datasource = getdv(viewstate("strsort").tostring())
 dgorder.databind()
 end sub
'分頁
 private sub dgorder_pageindexchanged(byval source as object, 
 byval e as system.web.ui.webcontrols.datagridpagechangedeventargs) handles dgorder.pageindexchanged
 '得到分頁的頁號(hào)
 dgorder.currentpageindex = e.newpageindex
 dgorder.datasource = getdv(viewstate("strsort").tostring())
 dgorder.databind()
 end sub 
為了知道用戶選擇的是哪些記錄,我們可以利用datagriditem的findcontrol得到checkbox的值,我們來添加一個(gè)按鈕,再寫如下代碼:
 private sub button1_click(byval sender as system.object, byval e as system.eventargs)
 handles button1.click
 dim item as datagriditem
 dim strscript as string
 strscript = "<script language=javascript>alert('"
 '循環(huán)表格的項(xiàng),findcontrol
 for each item in me.dgorder.items
 if ctype(item.findcontrol("cb"), system.web.ui.webcontrols.checkbox).checked then
 try
 strscript += item.cells(1).text & space(2)
 catch ex as exception
 end try
 end if
 next
 strscript += "被選擇!')</script>"
 registerclientscriptblock("系統(tǒng)消息", strscript)
 end sub
上面的代碼registerclientscriptblock添加java script腳本彈出對(duì)話框。(其實(shí)vb script的對(duì)話框比java script的對(duì)話框多更多的顯示和控制方式,但netscape的瀏覽器不支持,大家可根據(jù)相應(yīng)的項(xiàng)目在程序里選擇用哪種腳本)。
總結(jié):
datagrid是我們常用的web 控件,有時(shí)我們還可以和datalist混合使用,通過修改html頁,可以達(dá)到好的頁面效果。上面只是一個(gè)例子,為了便于清楚整個(gè)過程,我把數(shù)據(jù)訪問部分(sql)寫到了頁面中。在軟件開發(fā)中,我們一般把訪問數(shù)據(jù)的部分寫成數(shù)據(jù)層,頁面調(diào)用數(shù)據(jù)層得到數(shù)據(jù),這樣邏輯清晰,修改和維護(hù)都很方便。