【问题标题】:checking a radio button from it's name as a string从其名称中检查单选按钮作为字符串
【发布时间】:2014-12-22 23:13:58
【问题描述】:

假设我的表单上有 5 个单选按钮。

在我的代码中,我想检查 RadioButton3。 我将“RadioButton3”存储在字符串变量(RadName)中

我已经可以遍历表单上的控件了。当循环到达 RadioButton3 时,我该如何检查(并实际填充单选按钮)?

   For Each RadioButtn As Control In Me.gbWriteXML.Controls
        If (TypeOf RadioButtn Is RadioButton) Then
           ---code here for checking the radio button---
        End If
    Next

.gbWriteXML 是一个组框。只是为了避免任何混乱。我在想这样的事情:

If RadioButtn.Name = RadName Then
      RadName.Checked = True (or .PerformClick for that button)
End If

如何通过控件的名称实际获取与 RadName 字符串关联的控件? 我需要这段代码能够将单选按钮的名称作为硬编码字符串或在运行时输入到程序中,循环直到找到具有匹配名称的单选按钮,然后实际获取该单选按钮控件,并检查它以使其填充为蓝色。

【问题讨论】:

  • 将RadName.Checked = True 更改为RadioButtn.Checked = True。 Name 和 Checked 都只是 RadioButtn 对象的属性。 Visual Studio 为您在设计器中放置在窗体上的每个对象创建变量,并将变量命名为与 Name 属性相同的名称。这就是为什么您也可以在代码中直接使用它们的名称访问它们。

标签: vb.net loops controls


【解决方案1】:

不要循环。只需像这样使用Controls.Find() 搜索它:

    Dim RadName As String = "RadioButton3"
    Dim matches() As Control = Me.Controls.Find(RadName, True)
    If matches.Length > 0 AndAlso TypeOf matches(0) Is RadioButton Then
        Dim rb As RadioButton = DirectCast(matches(0), RadioButton)
        rb.Checked = True
    End If

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    • 2017-12-31
    • 2012-06-09
    • 2013-08-25
    • 2014-01-06
    相关资源
    最近更新 更多