creating controls programatically

frootmig

Member
Joined
Feb 23, 2006
Messages
5
Programming Experience
1-3
Hello,

I am having a small problem with the correct syntax to achieve my goal.

I am creating an application that needs to create controls dynamicaly from a hashtable, I have created a #table that conatins key and value pairs with the key being the control parameter and the value being the desired parameter value.

I am then creating a new instance of a control using the following code:

newControl = CType(Activator.CreateInstance(t), Control)

To populate the new controls parameters from a hash table I can use something like:

newControl.Left = ctrl.Item("Left")

But what I would like to be able to do is use the #tables key value as the parameter name(in red above) and and use a loop to build the control parameters, something like this:

Dim en As IDictionaryEnumerator = ctrl.GetEnumerator
While en.MoveNext

newControl.(ctrl.key) = ctrl.value

End While

I am unsure as to the correct syntax to achieve this if it is possible, it is probably me being daft.

I look forward to any sage advice that can be given

Many Thanks

Frootmig...
 
Something like this (some exception handling needed!)

VB.NET:
[COLOR=#0000ff]Private[/COLOR] [COLOR=#0000ff]Sub[/COLOR] createControls()
    [COLOR=#0000ff]Dim[/COLOR] t [COLOR=#0000ff]As[/COLOR] Type = [COLOR=#0000ff]GetType[/COLOR](Button)
    [COLOR=#0000ff]Dim[/COLOR] ctrl [COLOR=#0000ff]As[/COLOR] [COLOR=#0000ff]New[/COLOR] Hashtable
    ctrl.Add([COLOR=#800000]"Left"[/COLOR], 10)
    ctrl.Add([COLOR=#800000]"Top"[/COLOR], 200)
    ctrl.Add([COLOR=#800000]"Height"[/COLOR], 100)
    ctrl.Add([COLOR=#800000]"Width"[/COLOR], 250)
    ctrl.Add([COLOR=#800000]"Text"[/COLOR], [COLOR=#800000]"Hello Reflection"[/COLOR])
    [COLOR=#0000ff]Dim[/COLOR] control [COLOR=#0000ff]As[/COLOR] Control = [COLOR=#0000ff]DirectCast[/COLOR](Activator.CreateInstance(t), Control)
    [COLOR=#0000ff]For[/COLOR] [COLOR=#0000ff]Each[/COLOR] key [COLOR=#0000ff]As[/COLOR] [COLOR=#0000ff]String[/COLOR] [COLOR=#0000ff]In[/COLOR] ctrl.Keys
        [COLOR=#0000ff]Dim[/COLOR] info [COLOR=#0000ff]As[/COLOR] PropertyInfo = t.GetProperty(key)
        info.SetValue(control, ctrl(key), [COLOR=#0000ff]Nothing[/COLOR])
    [COLOR=#0000ff]Next[/COLOR]
    Controls.Add(control)
[COLOR=#0000ff]End[/COLOR] [COLOR=#0000ff]Sub[/COLOR]
 
Hi Don,

Many thanks I think this is what I am looking for, it was the passing the key text as a property that was causing me problems.

I will give it a try and let you know, i am at present building the database to hold all the control data.

Many Thanks again..

Frootmig....
 
Back
Top