Accessing Object by Name:String

Ok,
now I know how to check if an objext exists, the next step should be to obtain this object. Therefor I read the VS-Help of Reflection, but found no answers as in google too.

What would I like to Do

class myObjectsClass
dim myObject1 = new system.windows.forms.button
myObject1.text="OK"
dim myObject2 = new system.windows.forms.button
.......
public function getObjectByName(ByVal objName as String) as system.windows.forms.button
' This function should return the requested Object
' in case getObjectByName("myObject1") should return myObject1

end function
end class

Does someone has an idea how to do that



Answer this question

Accessing Object by Name:String

  • Michael_Giagnocavo

    Reflection let's you find a Type but not an object instance. In other words, you can find the Button class but not the Button1 object. If it is a form control you're looking for, you can use the Form.Controls collection. See this thread for some sample code in iterating through all the controls of a form, even ones that are placed on a container or usercontrol.



  • jawosis

    Ok, sorry - I found a way to solve my problem, although it was not the way I'd like to do it. After searching the web for a while, it now seems to me, that it's impossible to return an object without running a for-to or manage my objects in some kind of list.

    I will use a HashTable-Object to store my objects by name as key.

    The reason, why I prefer the list and not the iteration is, that I will have to search for some object very often during processing (some kind of interpreter for connection comunication).



  • jamba8

    A list/Dictionary/hastable/etc. is the way to go.

    Also consider this, even though you may access the object in that list, you can also store the references to objects in that list. For example, if you have a datagridview that displays objects, you can store an object reference in the tag property for a row, thus having direct access to that object.



  • Accessing Object by Name:String