开发者

Dynamically Reference an Object Property Using a String

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).TxtProper开发者_开发知识库tyName so that I can remove ".FirstName" from my code? Thanks!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜