Dynamically build code...

lidds

Junior Contributor
Joined
Nov 9, 2004
Messages
210
I have a list of button names that exist on my form in my DB, I have added the functionallity for the admin user to determine what buttons they wish to see i.e. the DB has column for the name and another column specifying true or false. What I would like to be able to do is build the VB code up form the DB.

An example code (not correct just to give you an idea)

Visual Basic:
  Do While myReader.Read
    ' get button name from DB
    dim buttonName as string = myReader("columnName")
    ' get button is visible (true or false) from DB
    dim buttonVis as boolean = myReader("columnVis")
    ' This is where I want to dynamically build the vb code using the above
    ' values
    me.buttonName.visible = buttonVis
  Loop

Is this possible

I hope this made sense.

Thanks

Simon
 
IngisKahn said:
A button is just a class like anything else; you can create and destroy them at your liesure.
Knowing how to use them dynamically is a whole different story.

If you feel like recompiling the code each time you use it, what you want would be possible. You could create the code in a string or string builder and compile it to an in-memory assembly, since .Net comes with VB and C# compilers built in. If you can't find any code example then let me know and I can point you in the right direction. I think that there is an example in the "Tutors Corner" forum under a title like "Scripting your application." You would need to use a standard interface, derive from a common base, or use reflection to have your application communicate with the compiled-on-the-fly classes. Certainly not a simple answer to a simple question.

It would certainly be possible, however, to use another, simpler, approach. (I'm sure IngisKahn will like this one better.) You can create the buttons on the fly, attatch handlers on the fly, store the objects in a dictionary collection, and access them via a string instead of an early bound member name. I would say that such a solution would be adequately dynamic.

Either way, I think that a little learning and experimenting will be needed on your part.
 
Its certainly possible, as its midnight off of the top of my head the only idea I have is extremely crude and I wouldn't recommend it as a final solution. But one way of achieving this would be to loop through the Controls property of the form (i.e. all the controls on the form) check if its type is button and if it's name is equal to buttonName then set its visibilty property to the appropriate value. I'm pretty sure there is a GetObject method that you can pass a type and a name but i'm too tired to look it up now.

EDIT:- Obviously this isn't particular dynamic in the manner that marble suggests, but it seemed to fit your requirements.
 
Last edited:
Back
Top