使用带控件名称的变量 [英] Using a variable with control names

查看:73
本文介绍了使用带控件名称的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家早上好



我有12个CheckBoxes的列表

(chk_Draw_1,chk_Draw_2等,直到chk_Draw_12)

包含在GroupBox中(称为grp_Drawing_Types)

- 没有在表单打开时检查。



一旦用户检查他需要的方框,程序需要确定哪些已被检查,只需获取Text属性。



使用VBA我可以编写一些代码,如:

Good morning everyone

I have a list of 12 CheckBoxes
(Called chk_Draw_1, chk_Draw_2 etc up to chk_Draw_12)
contained within a GroupBox (Called grp_Drawing_Types)
- none are Checked when the form is opened.

Once the user checks the boxes he requires, the program needs to determine which have been checked to simply get the Text property.

Using VBA I could write a bit of code like :

For x = 1 To 12
    If Me.Controls("chk_Draw_" & x).Value = True Then
        UsedBoxes(x) = Me.Controls("chk_Draw_" & x).Caption
    End If
Next





有谁知道Vb.Net中是否可以使用这种类型的例行程序?



我尝试了各种代码使用



Does anyone know if this type of routine would be possible in Vb.Net ?

I have tried various bits of code using

for each ctrl as control in me.controls
  ....





但我一直在做一个完整的哈希。



but I keep making a complete hash of it.

推荐答案

你可能只是创建一个复选框数组,例如

You might simply create an array of check boxes, e.g.
' fill properly the ellipses
Dim chkb As CheckBox() = {chk_Draw_1, chk_Draw_2, ..., chk_Draw_12}



然后使用它。


and then use it.


我建​​议添加事件处理程序 [ ^ ]并将复选框复选到列出(of T)泛型类 [ ^ ]。



I would suggest to add event handler[^] for each CheckBox and get checked checkboxes into List(of T) generic class[^].

Public Class Form1

    Private WithEvents oChk As CheckBox
    Private CheckedCheckBoxes As List(Of CheckBox) = New List(Of CheckBox)

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        For Each chb As CheckBox In Me.GroupBox1.Controls
            If chb.Checked Then CheckedCheckBoxes.Add(chb)
        Next

        'do what you want to do...
        
    End Sub



    Private Sub oChk_CheckStateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles oChk.CheckStateChanged
        Dim chb As CheckBox = CType(sender, CheckBox)
        MsgBox(chb.Name & " is Checked: " & chb.Checked)
    End Sub

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        For Each chb As CheckBox In Me.GroupBox1.Controls
            AddHandler chb.CheckStateChanged, AddressOf oChk_CheckStateChanged
        Next


    End Sub
End Class


自己解决(经过多次诅咒和挫折)



Solved it myself (after much cursing and frustration)

For Each ctrl In Me.grp_Drawing_Types.Controls
    If ctrl.checked = True Then
        TypeString = TypeString & ctrl.text & ", "
    End If
Next


这篇关于使用带控件名称的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆