GetProperty() and Bindingflags

quwiltw

Contributor
Joined
Sep 18, 2001
Messages
486
Location
Washington, D.C.
Anyone know a combination to find only overridden properties using GetProperty() of a Type? I keep getting ambiguousmatchexception because it finds both the base class' property and my overridden one. Here's a mock-up of what I'm trying to do.

My class:
Visual Basic:
Public Class NewTextBox
    Inherits System.Windows.Forms.TextBox

    Private m_strText As String = ""

    Public Overrides Property Text() As String
        Get
            Return m_strText
        End Get
        Set(ByVal Value As String)
            m_strText = Value
        End Set
    End Property
End Class

GetProperty attempt:
Visual Basic:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim typ As Type
        typ = Me.NewTextBox1.GetType()

        Dim prop As PropertyInfo
        prop = typ.GetProperty("Text")

        If Not prop Is Nothing Then
            prop.SetValue(Me.NewTextBox1, "My New Value", Nothing)
        Else
            MessageBox.Show("Not found.")
        End If

    End Sub

This returns ambigous match and I've tried several BindingFlag parameters to the GetProperty() method to no avail. Seems like it should be fairly easy.
 
Answer:
Visual Basic:
props = typ.GetProperty("Text", BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.DeclaredOnly)
In my opinion, this ain't exactly straightforward, oh well.
 
Whenever I use reflection to do things like that I always seem to get caught out by forgetting to specify BindingFlags.Instance - it's really annoying!
 
Back
Top