<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>
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>
当有人点击DataGrid中某个Detail按钮时,ASP.Net Web页面将执行回发,页面又将在服务器端执行。Page_Load事件处理程序将再次被激活,但是这次因为我们在执行回发,BindData()过程将不会被调用。此外detailsClicked事件处理程序将被执行。注意如果我们每次在页面装载时均将数据绑定至DataGrid(也就是说我们省略了If Not Page.IsPostBack检查),detailsClicked事件处理程序将不会执行,因为重新绑定DataGrid将会清空(flush out)ItemCommand事件。(请重新阅读上面的两段文字-根据各位对DataGrid的了解,你们很有可能忘记执行回发检查并导致DataGrid不能触发针对按钮的事件处理代码。相信我,这件事在我身上多次发生!J)