选择一下容器控件放入form中,本例子选用的是table,并且数据全部是从DB中读取出来的.动态生成多个checkbox,然后对checkbox的事件进行相应的处理:
For Each dr As DataRow In Me.DS.Tables(0).Rows'从DB中读取数据
chk = New CheckBox()
chk.Name = "chk_" & dr("skill_id").ToString()
chk.Text = dr("skill_id").ToString + "." + dr("description").ToString()
chk.Size = New Size(180, 17)
chk.AutoCheck = True
Me.tlp_employee_skill.Controls.Add(chk)'往容器里进行动态添加控件
Next
要应事件的处理,此函数只需要放到需要改变checkbox 的checked地方就行:
Private Sub CheckedChanged()
For Each ctr As Control In Me.tlp_employee_skill.Controls
If (ctr.GetType() Is GetType(CheckBox)) Then
If (CType(ctr, CheckBox).Checked = True) Then
Me.skillset = Me.skillset + CType(ctr, CheckBox).Name.Replace("chk_", String.Empty) + ","
End If
End If
Next
End Sub
从DB中读取数据,将对应的checkbox 的checked=true
Dim skillSetList() As String
skillSetList = dr("skill_set").ToString().Split(",".ToCharArray())
For Each skill As String In skillSetList
For Each ctr As Control In Me.tlp_employee_skill.Controls
If (ctr.GetType() Is GetType(CheckBox)) Then
If (ctr.Name.Replace("chk_", String.Empty) = skill) Then
CType(ctr, CheckBox).Checked = True
End If
End If
Next
Next