2015年7月1日 星期三

asp.net 動態產生CheckBox

參考引用來源
--

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Public Partial Class Default4
Inherits System.Web.UI.Page
Private WorkMch As String() = {"A", "B", "C", "D", "E", "F", _
"G", "H"}
'CheckBox的Text
Private Sub Page_Load(sender As Object, e As System.EventArgs) Handles Page.Load
If Not IsPostBack Then
AddControls()
End If
End Sub


Protected Overrides Sub LoadViewState(savedState As Object)
MyBase.LoadViewState(savedState)
'ViewState["controsladded"]似乎是由base繼承下來的,不可更改
If ViewState("controsladded") Is Nothing Then
AddControls()
End If
End Sub


Private Sub AddControls()
pnlCheckbox.Controls.Add(New LiteralControl(""))

Dim i As Integer = 0
While i < WorkMch.Length
Dim l_cbx As New CheckBox()
l_cbx.Text = WorkMch(i).ToString()
l_cbx.ID = "cbx" + WorkMch(i).ToString()
l_cbx.AutoPostBack = True
'pnlCheckbox為Panel控制項
pnlCheckbox.Controls.Add(New LiteralControl(""))
pnlCheckbox.Controls.Add(l_cbx)
pnlCheckbox.Controls.Add(New LiteralControl("
"))
If i > 0 AndAlso i Mod 4 = 3 AndAlso i <> WorkMch.Length - 1 Then
pnlCheckbox.Controls.Add(New LiteralControl("
")) ElseIf i = WorkMch.Length - 1 Then
pnlCheckbox.Controls.Add(New LiteralControl("
")) End If
'為自訂的checkbox掛上event
AddHandler l_cbx.CheckedChanged, New EventHandler(AddressOf(l_cbx_CheckedChanged))
System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
End While
pnlCheckbox.Controls.Add(New LiteralControl("
")) ViewState("controlsadded") = True
End Sub


Private Sub l_cbx(sender As Object, e As System.EventArgs) Handles l.cbx
Dim cbx As CheckBox = CType(sender, CheckBox)
Response.Write("CheckBox" + cbx.Text + " : " + cbx.Checked.ToString())
End Sub


Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim cbxA As New CheckBox()
cbxA = CType(pnlCheckbox.FindControl("cbxA"), CheckBox)
Response.Write(cbxA.Checked)
End Sub


Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click
pnlCheckbox.Controls.Clear()
End Sub


End Class

沒有留言:

張貼留言