DataGrid Web控件深度历险(3) part3

来源:岁月联盟 编辑:zhu 时间:2004-05-28
在本文第二部分我们研究了如何通过ButtonColumn标记在DataGrid中显示按钮。此外,我们考察了如何将事件处理程序与按钮的点击联系起来。下面我们将了解到如何判断DataGrid中哪一行的按钮被点击并且基于这些信息执行相应的动作。

判断哪一行的按钮被点击

回想一下点击按钮的事件处理程序定义如下:

Sub eventHandlerName(sender as Object, e as DataGridCommandEventArgs)
...
End Sub

DataGridCommandEventArgs类包含一个Item属性,该属性包含了触发该事件的源对象。Item属性是TableRow类的一个实例,它指向DataGrid中被点击的那一行。可使用Cells属性访问TableRow类中的列。例如有一个DataGrid,它的列信息定义如下:

<asp:DataGrid runat="server" ... >
<Columns>
<asp:ButtonColumn Text="Details" HeaderText="FAQ Details" CommandName="details" />
<asp:BoundColumn DataField="FAQID" HeaderText="FAQ ID" />
<asp:BoundColumn DataField="Description" HeaderText="FAQ Description" />
</Columns>
</asp:datagrid>

那么在点击按钮的事件处理程序中,可通过以下方法获得被点击行的某一列的值:

Sub detailsClicked(sender as Object, e As DataGridCommandEventArgs)
Dim buttonColumn as TableCell = e.Item.Cells(0)
Dim FAQIDColumn as TableCell = e.Item.Cells(1)
Dim DescColumn as TableCell = e.Item.Cells(2)

Dim buttonColText as String = buttonColumn.Text
Dim FAQIDColText as String = FAQIDColumn.Text
Dim DescColText as String = DescColumn.Text
End Sub

示例运行结果如下:

更新按钮事件处理程序后的DataGrid示例

本示例展示了一个包含Detail按钮的DataGrid Web控件并演示了当按下按钮时如何触发一段代码。注意点击某个Detail按钮后你会看到被点击按钮所在行的信息。

Value of Clicked Button Column Text:
Value of FAQID Column Text: 181
Value of Clicked Description Column Text: How can I format numbers and date/times using ASP.NET? For example, I want to format a number as a currency.

FAQ Details
FAQ ID
FAQ Description


144
Where can I host my ASP Web site for free (similar to GeoCities or Tripod or any of the many other free Web site sites)?


181
How can I format numbers and date/times using ASP.NET? For example, I want to format a number as a currency.






源代码

<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script language="vb" runat="server">
Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack then
BindData()
End If
End Sub


Sub BindData()
'1. Create a connection
Dim myConnection as New SqlConnection(ConfigurationSettings.AppSettings("connectionString"))

'2. Create the command object, passing in the SQL string
Const strSQL as String = "sp_Popularity"
Dim myCommand as New SqlCommand(strSQL, myConnection)

'Set the datagrid's datasource to the datareader and databind

myConnection.Open()
dgPopularFAQs.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
dgPopularFAQs.DataBind()
End Sub


Sub dispDetails(sender as Object, e As DataGridCommandEventArgs)
Dim buttonColumn as TableCell = e.Item.Cells(0)
Dim FAQIDColumn as TableCell = e.Item.Cells(1)
Dim DescColumn as TableCell = e.Item.Cells(2)

Dim buttonColText as String = buttonColumn.Text
Dim FAQIDColText as String = FAQIDColumn.Text
Dim DescColText as String = DescColumn.Text

lblBCT.Text = buttonColText
lblFCT.Text = FAQIDColText
lblDCT.Text = DescColText
End Sub
</script>

<form runat="server">
<b>Value of Clicked Button Column Text</b>:
<asp:label id="lblBCT" runat="server" /><br />

<b>Value of FAQID Column Text</b>:
<asp:label id="lblFCT" runat="server" /><br />

<b>Value of Clicked Description Column Text</b>:
<asp:label id="lblDCT" runat="server" /><br />

<asp:DataGrid runat="server" id="dgPopularFAQs"
BackColor="#eeeeee" Width="85%"
HorizontalAlign="Center"
Font-Name="Verdana" CellPadding="4"
Font-Size="10pt" AutoGenerateColumns="False"
OnItemCommand="dispDetails">
<HeaderStyle BackColor="Black" ForeColor="White" Font-Bold="True" HorizontalAlign="Center" />
<AlternatingItemStyle BackColor="White" />

<Columns>
<asp:ButtonColumn Text="Details" HeaderText="FAQ Details" CommandName="details" ButtonType="PushButton" />
<asp:BoundColumn DataField="FAQID" HeaderText="FAQ ID" />
<asp:BoundColumn DataField="Description" HeaderText="FAQ Description" />
</Columns>
</asp:datagrid>
</form>

请仔细检查上面的示例。你可能注意到的第一件事就是按钮列不包含任何文本。这是因为仅需通过HTML即可显示按钮,因此TableCell的Text属性返回了一个空字符串。

在本文开始部分我讲述了一个电子商务公司的场景,该公司希望显示部分货运信息,但同时提供显示所有货运信息的选择。到目前为止的示例中,我们仅显示了sp_Popularity存储过程返回列中的一小部分列。想象一下我们仅希望显示最受欢迎的常见问题的描述列,然后提供一个Detail按钮允许用户查看某个常见问题的其余信息。

虽然我们不希望在DataGrid中显示FAQID列,但是我们仍然需要为detialsClicked事件处理程序提供该信息,因为它数据库中表的关键字并唯一标识了每个常见问题。通过对DataGrid标记进行小小的改动(在与数据库中FAQID列对应的BoundColumn标记中增加Visible= "False"),我们仍然能够传递该信息。此改动隐藏了FAQID列,但仍然允许detailClicked事件处理程序访问某个常见问题的标识(通过e.Item.Cells(1).Text)。

因此我们所要做的就是改写detailsClicked事件处理程序,以便当它被触发时获得用户希望显示的那个常见问题的信息,然后再显示该常见问题的详细信息。在阅读了一系列关于如何使用DataGrid的文章后,当需要显示数据库中的数据时,你的第一个想法应该就是使用DataGrid。因此我们的页面看起来应该是这样:

<script language="vb" runat="server">
Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack then
BindData() 'Only bind the data on the first page load
End If
End Sub


Sub BindData()
'Make a connection to the database
'Databind the DataReader results to the gPopularFAQs DataGrid.
End Sub


Sub detailsClicked(sender as Object, e As DataGridCommandEventArgs)
'Get detailed information about the selected FAQ and bind
'the database results to the dgFAQDetails DataGrid
End Sub
</script>

<form runat="server">
<asp:DataGrid runat="server" id="dgFAQDetails" ... >
...
</asp:datagrid>

<asp:DataGrid runat="server" id="dgPopularFAQs" ... >
<Columns>
<asp:ButtonColumn Text="Details" HeaderText="FAQ Details"
ButtonType="PushButton" />
<asp:BoundColumn DataField="FAQID" Visible="False" />
<asp:BoundColumn DataField="Description" HeaderText="FAQ Description" />
</Columns>
</asp:datagrid>
</form>

示例运行结果如下:

本示例展示了如何在DataGrid的每一行中显示概要信息和一个Detail按钮,当按钮被点击时,对所选择的数据项显示其余信息。

Category Name
FAQ Description
Views
Author
Author's Email
Date Added

Getting Started
Where can I host my ASP Web site for free (similar to GeoCities or Tripod or any of the many other free Web site sites)?
163,148
Scott Mitchell
mitchell@4guysfromrolla.com
03-20-2001




FAQ Details
FAQ Description


Where can I host my ASP Web site for free (similar to GeoCities or Tripod or any of the many other free Web site sites)?





源代码

<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script language="vb" runat="server">
Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack then
BindData()
End If
End Sub


Sub BindData()
'1. Create a connection
Dim myConnection as New SqlConnection(ConfigurationSettings.AppSettings("connectionString"))

'2. Create the command object, passing in the SQL string
Const strSQL as String = "sp_Popularity"
Dim myCommand as New SqlCommand(strSQL, myConnection)

'Set the datagrid's datasource to the datareader and databind
myConnection.Open()
dgPopularFAQs.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
dgPopularFAQs.DataBind()
End Sub


Sub dispDetails(sender as Object, e As DataGridCommandEventArgs)
Dim FAQID as Integer = Convert.ToInt32(e.Item.Cells(1).Text)

'Get information about the particular FAQ
Dim myConnection as New SqlConnection(ConfigurationSettings.AppSettings("connectionString"))

'2. Create the command object, passing in the SQL string
Dim strSQL as String = "spGetFAQ"
Dim myCommand as New SqlCommand(strSQL, myConnection)

myCommand.CommandType = CommandType.StoredProcedure

' Add Parameters to SPROC
Dim parameterFAQId as New SqlParameter("@FAQID", SqlDbType.Int, 4)
parameterFAQId.Value = FAQID
myCommand.Parameters.Add(parameterFAQId)


'Set the datagrid's datasource to the datareader and databind
myConnection.Open()
dgFAQDetails.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
dgFAQDetails.DataBind()

dgFAQDetails.Visible = True 'Make the FAQ Details DataGrid visible
End Sub
</script>

<form runat="server">

<asp:DataGrid runat="server" id="dgFAQDetails"
BackColor="#eeeeee" Width="90%"
HorizontalAlign="Center"
Font-Name="Verdana" CellPadding="4"
Font-Size="10pt" AutoGenerateColumns="False"
Visible="False">
<HeaderStyle BackColor="Black" ForeColor="White" Font-Bold="True" HorizontalAlign="Center" />
<AlternatingItemStyle BackColor="White" />

<Columns>
<asp:BoundColumn DataField="CatName" HeaderText="Category Name" />
<asp:BoundColumn DataField="Description" HeaderText="FAQ Description" />
<asp:BoundColumn DataField="ViewCount" DataFormatString="{0:#,###}"
HeaderText="Views" ItemStyle-HorizontalAlign="Center" />
<asp:BoundColumn DataField="SubmittedByName" HeaderText="Author" />
<asp:BoundColumn DataField="SubmittedByEmail" HeaderText="Author's Email" />
<asp:BoundColumn DataField="DateEntered" HeaderText="Date Added"
DataFormatString="{0:MM-dd-yyyy}" />
</Columns>
</asp:datagrid>
<p>
<asp:DataGrid runat="server" id="dgPopularFAQs"
BackColor="#eeeeee" Width="85%"
HorizontalAlign="Center"
Font-Name="Verdana" CellPadding="4"
Font-Size="10pt" AutoGenerateColumns="False"
OnItemCommand="dispDetails">
<HeaderStyle BackColor="Black" ForeColor="White" Font-Bold="True" HorizontalAlign="Center" />
<AlternatingItemStyle BackColor="White" />

<Columns>
<asp:ButtonColumn Text="Details" HeaderText="FAQ Details" ButtonType="PushButton" />
<asp:BoundColumn DataField="FAQID" Visible="False" />
<asp:BoundColumn DataField="Description" HeaderText="FAQ Description" />
</Columns>
</asp:datagrid>
</form>

需要注意的第一件事就是ASP.Net Web页面中有两个DataGrid。第一个(dgFAQDetails)用于显示一个特定常见问题的详细信息。第二个(dgPopularFAQs)是我们一直用来显示最受欢迎的10个常见问题的那个DataGrid。注意dgPopularFAQs DataGrid的FAQID绑定列被修改了,增加了Visible="False",以便FAQID列不在dgPopularFAQs DataGrid的输出中显示。

在过去的三篇文章中我们研究了将数据库查询的结果显示在HTML表格中(第一篇),在无需编写代码的情况下美化HTML表格(第二篇)和本篇中如何在每列中增加按钮并对事件进行响应。我们将在今后的文章中看到“增加按钮并当按钮被点击时进行响应”的概念可被扩展以允许进行排序、分页和编辑数据。回见……

祝编程愉快!