如何检查在通过表单控件迭代时是否选中复选框 [英] How to check if a checkbox is checked when iterating through form controls

查看:126
本文介绍了如何检查在通过表单控件迭代时是否选中复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为表单上的每个复选框设置一个注册表项,但在下面的代码块中,我收到错误'Checked'不是'System'的成员。 Windows.Forms.Control'

I'm trying to set a registry key for every checkbox on a form, but in the following block of code, I'm receiving the error 'Checked' is not a member of 'System.Windows.Forms.Control'

有人可以帮我找出为什么会收到这个错误吗?

Can somebody please help me find out why I'm getting this error?

' Create the data for the 'Servers' subkey
Dim SingleControl As Control    ' Dummy to hold a form control
For Each SingleControl In Me.Controls
    If TypeOf SingleControl Is CheckBox Then
        Servers.SetValue(SingleControl.Name, SingleControl.Checked) ' Error happening here
    End If
Next SingleControl


推荐答案

在使用Checked属性之前,应该将控件转换为CheckBox。 >
直接使用控制变量并且此类型(Control)没有Checked属性

You should convert your control to a CheckBox before using the Checked property.
You use directly the Control variable and this type (Control) doesn't have a Checked property

Dim SingleControl As Control    ' Dummy to hold a form control
For Each SingleControl In Me.Controls
    Dim chk as CheckBox = TryCast(SingleControl, CheckBox)
    If chk IsNot Nothing Then
        Servers.SetValue(chk.Name, chk.Checked) 
    End If
Next 

更好的方法是使用 Enumerable.OfType

Dim chk As CheckBox
For Each chk In Me.Controls.OfType(Of CheckBox)()
    Servers.SetValue(chk.Name, chk.Checked) 
Next 

这会删除将通用控件转换为正确类型的必要,并测试转换是否成功

this removes the need to convert the generic control to a correct type and test if the conversion was successfully

这篇关于如何检查在通过表单控件迭代时是否选中复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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