简体   繁体   English

如果控件具有属性,则更改控件的属性值

[英]Change property value of control if the control has the property

Some controls on my form have a DataSource property on the control itself, some dont.我的表单上的某些控件在控件本身上有一个 DataSource 属性,有些则没有。

I want to loop through all the controls and set the DataSource to Nothing if the control has the property.如果控件具有该属性,我想遍历所有控件并将 DataSource 设置为 Nothing。 It would work something like this.它会像这样工作。

Private Sub ClearAllDatabindings()
    If _dataBindingsSet = True Then
        For Each ctrl As Control In Me.Controls
            ClearDataBindings(ctrl)
            SetDatasourceToNothing(ctrl) '-- This is the piece idk how to Write.
        Next
    End If
End Sub

I am not sure how to check this during run-time.我不知道如何在运行时检查这个。

As requested by OP, In C#, using System.Reflection, you could do something like this to check if a class / its instance has property or not:根据 OP 的要求,在 C# 中,使用 System.Reflection,您可以执行以下操作来检查类/其实例是否具有属性:

//for class type
var props = typeof(MyClass).GetProperties();
if (props == null || props.Length <= 0) { //does not have property
     //do something
}

//for class instance
var props = classInstance.GetType().GetProperties();
if (props == null || props.Length <= 0) { //does not have property
     //do something
}

To check for specific property:要检查特定属性:

 var prop = props.SingleOrDefault(x => x.Name == "propName");
 if(prop != null){
     //has that property
     //do changing of your Control here
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM