动态产生表格及事件拦截 Part2
在之前 动态产生表格及事件拦截 的文章中,有示范如何“动态产生了 3 列 2 栏的表格及事件拦截”;本文将以这个范例延伸,当按一下按钮就动态在表格中加入一笔新的数据列。
首先在页面上放置一个 的 Button,设定其属性 UseSubmitBehavior="False" ,在 aspx 中的程序如下
在此范例中,利用了一个 HiddenField 来记录 Table 的数据列数,并由 Request.Form("__EVENTTARGET") 判断是否由 btnAddRow 按钮产生的 PostBack。
*.aspx.vb
Partial Class _Default
Inherits System.Web.UI.Page
Private FRowCount As Integer
Private FRowCountField As New HiddenField() FRowCountField As New HiddenField()
'''
''' 动态产生 Table。
'''
Private Sub CreateTable() Sub CreateTable(ByVal RowCount As Integer)
Dim oTable As New Table()
Dim oRow As TableRow
Dim oCell As TableCell
Dim oButton As Button
Dim oTextBox As TextBox
Dim N1 As Integer
Me.Form.Controls.Add(oTable)
'建立3列1栏的,其中第1栏置放 Button,第2栏置放 TextBox
For N1 = 1 To RowCount
oRow = New TableRow()
oTable.Rows.Add(oRow)
oCell = New TableCell()
oRow.Cells.Add(oCell)
oButton = New Button
oButton.Text = "Button" & N1.ToString()
'将 Button 的 Click 事件导向 Button_Click 函数
AddHandler oButton.Click, AddressOf Button_Click
oCell.Controls.Add(oButton)
oCell = New TableCell()
oRow.Cells.Add(oCell)
oTextBox = New TextBox()
oTextBox.Text = "TextBox" & N1.ToString()
oCell.Controls.Add(oTextBox)
Next
End Sub
Protected Sub Page_Init() Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
FRowCountField.ID = "__RowCount"
Me.Form.Controls.Add(FRowCountField)
'取得上次记录的数据列数
If Me.Request.Form(FRowCountField.UniqueID) Is Nothing Then
FRowCount = 0
Else
FRowCount = CInt(Me.Request.Form(FRowCountField.UniqueID))
End If
'由 Request.Form("__EVENTTARGET") 判断是否由 btnAddRow 按钮产生的 PostBack
If Me.Request.Form("__EVENTTARGET") = btnAddRow.UniqueID Then
FRowCount = FRowCount + 1
End If
CreateTable(FRowCount) '动态产生 Table。
End Sub
Protected Sub Page_Load() Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
FRowCountField.Value = FRowCount.ToString()
End Sub
'Table 中所有的 Button 的 Click 事件导向函数
Protected Sub Button_Click() Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim oButton As Button
Dim oRow As TableRow
Dim oCell As TableCell
Dim oTextBox As TextBox = Nothing
oButton = CType(sender, Button)
oCell = CType(oButton.Parent, TableCell)
oRow = CType(oCell.Parent, TableRow)
'取得内含 TextBox 的 Cell,即第2栏
oTextBox = CType(oRow.Cells(1).Controls(0), TextBox)
oTextBox.Text = oButton.Text
End Sub
End Class
ASP.NET 魔法学院