日期:2009-10-20  浏览次数:20461 次

点击按钮时让一些事情发生

现在已将按钮添加到DataGrid中了,我们希望将服务器端的代码与按钮关联起来,这样当按钮被点击时可发生一些动作。在认识到DataGrid中的ButtonColumn按钮被点击时ItemCommand事件将被触发后,那么我们就可为这个事件编写服务器端的事件处理程序。这个事件处理程序必须定义如下:


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

一旦在服务器端代码块(或代码后置页)中定义了此过程,你可通过在DataGrid的标记中增加OnItemComman属性的方法将DataGrid的事件与该事件处理程序联系起来,如下所示:

<ASP:datagrid runat="server"
...
OnItemCommand="eventHandlerName">
...
</ASP: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 DataGrid.
End Sub


Sub detailsClicked(sender as Object, e As DataGridCommandEventArgs)
Response.Write("You clicked one of the details buttons!")
End Sub
</script>

<form runat="server">
<ASP:DataGrid runat="server" ... >
...
</ASP:datagrid>
</form>
示例运行结果如下:

包含事件处理程序的DataGrid

本示例显示一个包含Detail按钮的DataGrid Web控件并演示了当按下按钮时如何触发一段代码。点击某个Detail按钮,你将会在Status文本旁看到一个消息,他指出了你点击了这个按钮!

Status: You clicked one of the details buttons!

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)
lblOutput.Text = "You clicked one of the details buttons!"
End Sub
</script>

<form runat="server">
<b>Status:</b> <ASP:label id="lblOutput" runat="server" Font-Italic="True" />
<p>

<ASP:DataGrid runat="server" id="dgPopularFAQs"
BackColor="#eeeeee" Width="85%"
HorizontalAlign="Center"
Font-Name="Verdana" CellPadding="4"