Home > Back-end >  vb.net: How to adress form items dynamically
vb.net: How to adress form items dynamically

Time:07-22

I have a form in vb.net with LOTS of text- and comboboxes. Now i do want to apply some settings to them, e.g. visibility, location and so on during runtime. The information on what to apply is complex and is stored in my database together with the name of the given item, e.g. name=textbox1, visibility=true, location x = bla, location y= bla and so on.

My question is: Is it somehow possible to use the string in the field "name" to adress the object in the code like this:

ConvertToFormObject(name).visible=visibility 

so that i could apply the settings with a single loop rather than hardcoding the information in the database to all the items. Also the settings should be applied spontanously, when e.g. some event triggers were triggered.

Thanks!

CodePudding user response:

You can index the Controls collection of the form by name to get the control with that Name value, e.g.

Dim cntrl As Control = Controls("TextBox1")

This assumes that all the controls of interest are on the form directly. If they are all in the same child container then use the Controls collection of that container. If they might be in different containers, e.g. a Panel and a GroupBox, then you can call Find, e.g.

Dim cntrl As Control = Controls.Find("TextBox1", True).First()

Note that Find returns a Control array, because the Name of each control in a container must be unique but multiple containers can each contain a control with the same Name. Assuming that you have used unique Name values form-wide, you just call First or Single or index the array with zero.

  • Related