日期:2012-05-05  浏览次数:20537 次

首先:创建为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>