在DataGrid中為Footer添加自定義內容
2024-07-21 02:23:08
供稿:網友
本文來源于網頁設計愛好者web開發社區http://www.html.org.cn收集整理,歡迎訪問。首先:創建為page_load事件編寫數據綁定的代碼:
<%@ page language="vb" %>
<%@ import namespace="system.data" %>
<%@ import namespace="system.data.sqlclient" %>
<p>
<script runat="server">
sub page_load(sender as object, e as eventargs)
dim myconnectionstring as string = "data source=.;initial catalog=northwind;user id=sa;password=;"
dim myconnection as sqlconnection = new sqlconnection(myconnectionstring)
dim mycommand as sqlcommand = new sqlcommand("select * from categories", myconnection)
dim mydatareader as sqldatareader
try
myconnection.open()
mydatareader = mycommand.executereader(commandbehavior.closeconnection)
mydatagrid.datasource = mydatareader
mydatagrid.databind()
catch myexception as exception
response.write("數據錯誤:" & myexception.tostring())
finally
if not mydatareader is nothing then
mydatareader.close()
end if
end try
end sub
其次:創建onitemdatabound事件,在onitemdatabound事件中,我們可以對datagrid中每行進行數據綁定時進行檢測。這里我們只添加footer部分的內容,因此,我們只檢測datagrid中的footer部分。下面是 datagrid中幾種itemtypes類型。
item type description
header datagrid控件的heading部分
footer datagrid控件的footer部分
item datagrid控件中每個條目
alternatingitem datagrid控件的alternating條目
selecteditem datagrid控件的selected條目
edititem datagrid控件的可編輯條目
separator datagrid控件每個條目之間的分割部分
pager datagrid控件的page selection部分
最后:一旦我們檢測到當前是footer部分,就可以添加我們的動態內容。這里我在第二列添加一個鏈接。
public sub mydatagrid_itemdatabound(sender as object, e as datagriditemeventargs)
'只有類型為footer的時候進行執行
if(e.item.itemtype = listitemtype.footer )
dim myhyperlink as hyperlink = new hyperlink()
if not request.querystring("id") = nothing then
myhyperlink.text = "添加內容"
myhyperlink.navigateurl = "adddetail.aspx?id=" & request.querystring("id")
else
myhyperlink.text = "沒有添加內容"
end if
'cells從0開始
e.item.cells(1).controls.add(myhyperlink)
end if
end sub
</script>
下面是aspx頁面部分:
<html>
<head>
</head>
<body>
<form runat="server">
<asp:datagrid id="mydatagrid"
runat="server"
showfooter="true"
onitemdatabound="mydatagrid_itemdatabound"
enableviewstate="false">
</asp:datagrid>
</form>
</body>
</html>