動態產生表格及事件攔截

摘要:動態產生表格及事件攔截

在下面的範例中,動態產生了 3 列 2 欄的表格,第 1 欄的 Cell 中含 Button 控制項,第 2 欄的 Cell 中含 TextBox 控制項;

其中攔截了所有 Button 事件導向同一函式,當按下每一列的 Button 時,它會去改變該列的 TextBox 的內容。

01 Partial Class _Default
02     Inherits System.Web.UI.Page
03
04     Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
05         Dim oTable As New Table()
06         Dim oRow As TableRow
07         Dim oCell As TableCell
08         Dim oButton As Button
09         Dim oTextBox As TextBox
10         Dim N1 As Integer
11
12         Me.Form.Controls.Add(oTable)
13         '建立3列1欄的,其中第1欄置放 Button,第2欄置放 TextBox
14         For N1 = 1 To 3
15             oRow = New TableRow()
16             oTable.Rows.Add(oRow)
17
18             oCell = New TableCell()
19             oRow.Cells.Add(oCell)
20             oButton = New Button
21             oButton.Text = "Button" & N1.ToString()
22             '將 Button 的 Click 事件導向 Button_Click 函式  
23             AddHandler oButton.Click, AddressOf Button_Click
24             oCell.Controls.Add(oButton)
25
26             oCell = New TableCell()
27             oRow.Cells.Add(oCell)
28             oTextBox = New TextBox()
29             oTextBox.Text = "TextBox" & N1.ToString()
30             oCell.Controls.Add(oTextBox)
31         Next
32     End Sub

33
34     'Table 中所有的 Button 的 Click 事件導向函數  
35     Protected Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
36         Dim oButton As Button
37         Dim oRow As TableRow
38         Dim oCell As TableCell
39
40         Dim oTextBox As TextBox = Nothing
41
42         oButton = CType(sender, Button)
43         oCell = CType(oButton.Parent, TableCell)
44         oRow = CType(oCell.Parent, TableRow)
45
46         '取得內含 TextBox 的 Cell,即第2欄
47         oTextBox = CType(oRow.Cells(1).Controls(0), TextBox)
48         oTextBox.Text = oButton.Text
49     End Sub

50
51 End Class

ASP.NET 魔法學院