检查是否可以检查控件?

时间:2012-11-19 15:00:46

标签: vb.net winforms checked

有没有办法检查并为支持它的未指定Windows控件设置Checked属性?

当然,有蛮力方法:

If TypeOf (control) Is Windows.Forms.CheckBox Then
    Dim chk As Windows.Forms.CheckBox = control
    chk.Checked = Boolean.Parse(sText)
ElseIf TypeOf (control) Is Windows.Forms.RadioButton Then
    Dim rdo As Windows.Forms.RadioButton = control
    rdo.Checked = Boolean.Parse(sText)
ElseIf TypeOf (control) Is Windows.Forms.DateTimePicker Then
    Dim dte As Windows.Forms.DateTimePicker = control
    dte.Checked = Boolean.Parse(sText)
etc...

然而,我觉得这很难看,而且我可能会错过任何控件。

似乎没有支持该属性的超类,即使CheckBoxRadioButton也是如此。此外,尝试简单地设置control.Checked将无法编译。

如果您对我的目标感到好奇,我希望创建一个通用表来存储命名控件的默认值。

1 个答案:

答案 0 :(得分:3)

如果你真的想检查是否存在任何名为Checked的属性,那么你需要使用反射:

control.GetType().GetProperty("Checked") IsNot Nothing

(请注意,如果Checked超载,则会抛出异常。)

但你真的只想保存Checked的{​​{1}}属性吗?看起来你正在寻找一个清单:

DateTimePicker