2

I'm trying to reference a public property from a string. How can this be done in vb.net? I have the text value of "FirstName" stored in strucParam(i).TxtPropertyName.

This is what I'm currently doing:

Dim tmpValue As String
Dim ucAppName As UserControl_appName = CType(Parent.FindControl(strucParam(i).ParentFindControl), UserControl_appName)

tmpValue = ucAppName.FirstName.Text

How can I use the value in strucParam(i).TxtPropertyName so that I can remove ".FirstName" from my code? Thanks!

crjunk
  • 949
  • 4
  • 21
  • 40

1 Answers1

1

This is basically a duplicate of this question, but I'll answer it for you since you're a VB user and probably didn't consider C# in your searches.

Suppose you have an object of any type stored in a variable called objObject, and the name of the property stored in a variable called strPropertyName. You do the following:

tmpValue = objObject.GetType().GetProperty(strPropertyName).GetValue(objObject, Nothing)

As a final note: please, please consider dropping pseudo-Hungarian notation. It's of no value when working with a statically typed language like VB.NET.

Edit:

The FirstName property is in reality a text box. So don't I need to somehow reference .Text in the code?
tmpFirstName = ucAppName.GetType().GetProperty(strucParam(i).PropertyName).GetValue(objAppNav, Nothing)

Try this:

Dim textBox as TextBox
Dim tmpValue as String

textBox = CType(ucAppName.GetType().GetProperty(strucParam(1).PropertyName).GetValue(objAppNav, Nothing), TextBox)
tmpValue = textBox.Text

Basically, you have to cast the value of the property to a TextBox type, then grab the Text property from it.

Community
  • 1
  • 1
Randolpho
  • 55,384
  • 17
  • 145
  • 179
  • I was unable to use null. I had to substitute it with Nothing. When running the following code, I get an "Object does not match target type" error. The FirstName property is in reality a text box. So don't I need to somehow reference .Text in the code? tmpFirstName = ucAppName.GetType().GetProperty(strucParam(i).PropertyName).GetValue(objAppNav, Nothing) – crjunk Jan 21 '11 at 18:12
  • @crjunk: my bad, I'm a C# guy and forgot to translate. I'll edit. – Randolpho Jan 21 '11 at 18:32
  • Thank you! Thank you! In honor of your help, I will no longer use pseudo-Hungarian notation. :) I had a typo in the code I posted here. My final solution was: Dim textBox As TextBox textBox = CType(ucAppName.GetType().GetProperty(strucParam(i).PropertyName).GetValue(ucAppName, Nothing), TextBox) – crjunk Jan 21 '11 at 18:55