How to convert the values in an Object into String

G

Guest

Hello,

Need an easy way to Display the property values of an object (dynamically)

ie I need to show the values of an Object in a rich text box.


Background : We have a form, with a rich text box, where we want to display
the values of any given object (say customer, order etc). We declared (Dim
Obj as New Object) and assigned our application object. Now we want to print
as Text (string) the values of Obj.

Issue : We tried using Obj.ToString (similar to java), but here the default
implementation is to display the Name/type of the object rather than the
values. Is there any way we can get this to work without implementing a
toString in Each of our classes. (We really want to avoid this as there are
quite a few classes)

Is there any way to loop thro the properties of a class and print them /or
any other solution/ideas

For example:
I've created an Object "obj"
the "obj" contains the following properties:
name
Description
.....
.....
.....
Here i need to get the values of the Properties(Attributes) in a rich text
box..
but i dont want to get the values as
obj.name
obj.Descriprion
....
....
and so on.

I want it in a single or simple code, no matter how many properties are there
 
C

Carlos J. Quintero [.NET MVP]

Hi Peter,

Yes, using reflection:


Public Overrides Function ToString() As String

Dim objType As Type
Dim colPropertyInfo() As System.Reflection.PropertyInfo
Dim objPropertyInfo As System.Reflection.PropertyInfo
Dim sResult As String

objType = Me.GetType()

colPropertyInfo = objType.GetProperties(Reflection.BindingFlags.Instance Or
Reflection.BindingFlags.Public Or Reflection.BindingFlags.GetProperty)

For Each objPropertyInfo In colPropertyInfo

sResult &= objPropertyInfo.Name & " = " & objPropertyInfo.GetValue(Me,
Nothing).ToString ' TODO: check for nulls
sResult &= Microsoft.VisualBasic.ControlChars.CrLf

Next

Return sResult

End Function



--

Best regards,

Carlos J. Quintero

MZ-Tools: Productivity add-ins for Visual Studio .NET, VB6, VB5 and VBA
You can code, design and document much faster.
Free resources for add-in developers:
http://www.mztools.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top