• 0

VB.Net - Dynamically accessing controls then accessing them after


Question

Right, I have some code that dynamically creates controls that I need, and obviously you can give them a name and what have you.

The controls will be created on form load, yet how do I access the controls after I've added them?

VB.Net doesn't seem to know they are they due to me generating them at run time.

Any ideas?

[Just Read the Topic Title and realised i've typed a big steaming pile of ****. Lovely.]

10 answers to this question

Recommended Posts

  • 0

OK, you've created the control, say a TextBox, the page has loaded, the user enters their input, the form is submitted and you want to get the value that the person entered, but it always turns up with no value in it?

  • 0
  Jelly2003 said:
OK, you've created the control, say a TextBox, the page has loaded, the user enters their input, the form is submitted and you want to get the value that the person entered, but it always turns up with no value in it?

No. Created a textbox using Code and not the IDE at runtime, but its not accessible? after you've created it you can't access it by the name you've created for it.

  • 0

If you dynamically create a control the "name" property means nothing... The Name property is for the IDE only and has no meaning at runtime

say you make a control like this

public class MyForm

Dim MyControl as new TextBox

public sub new

Me.Controls.Add(MyControl) ' add to form

with MyControl

.size = new size(21,100)

.Location = new Point(10,10)

end With

end sub

public sub UpdateControlsText

' Access the control now with the object you made in the class outside of a sub or function

MyControl.Text = "Text Here"

End Sub

end class

not that hard eh? anytime you make a control inside a sub though you need a reference to the control so you can access it outside that sub also!

  • 0

Wel, no doubt that you are adding them to the control container of the form (<form>.Controls) ? If so, you need to iterate through that to find your control, you may have to do it recusively if it is a nested control.

The best way to do this, is to apply a unique value to either the name, or the tag property of the control at runtime (i.e during the control generation):

Public Function FindControl(parent As Control, ident As String) As Control
   Dim control As Control
   For Each child As Control In parent.Controls
	  If (child.Tag.Equals(ident, StringComparer.InvariantCultureIgnoreCase)) Then
		 control = child
		 Exit For
	  End If
   End For
   Return control
End Function

Start with passing the main form as the parent control.

  • 0

Assuming that you're using ASP.net and not Windows Forms then you could use the "FindControl" method (provided that it implements it).

Object.FindControl("ControlName")

or

Object.FindControl("ControlName", true)

To recursively search the controls.

I am a C# guy so you would need to do some research on the VB.net way of doing it, but it will be very much the same.

  • 0
  neufuse said:
If you dynamically create a control the "name" property means nothing... The Name property is for the IDE only and has no meaning at runtime

say you make a control like this

public class MyForm

Dim MyControl as new TextBox

public sub new

Me.Controls.Add(MyControl) ' add to form

with MyControl

.size = new size(21,100)

.Location = new Point(10,10)

end With

end sub

public sub UpdateControlsText

' Access the control now with the object you made in the class outside of a sub or function

MyControl.Text = "Text Here"

End Sub

end class

not that hard eh? anytime you make a control inside a sub though you need a reference to the control so you can access it outside that sub also!

  Jelly2003 said:
Assuming that you're using ASP.net and not Windows Forms then you could use the "FindControl" method (provided that it implements it).

Object.FindControl("ControlName")

or

Object.FindControl("ControlName", true)

To recursively search the controls.

I am a C# guy so you would need to do some research on the VB.net way of doing it, but it will be very much the same.

Its VB.NET but thanks for the PM anyway. And to the first reply, I thought of that but I have no idea how many controls i am going to have, therefore I'd need an array but not knowing how big it is, how would I allocate for that in .Net?

  • 0
  MiG- said:
Its VB.NET but thanks for the PM anyway. And to the first reply, I thought of that but I have no idea how many controls i am going to have, therefore I'd need an array but not knowing how big it is, how would I allocate for that in .Net?

why would you need an array? if you add it to a container control such as a form or panel that control / form has a controls property which you can use to reference controls that have been added to the form / container... that would be the only case you'd want to specify a "name" for a control then you could do a string.compare to compare the name of the control and the item you are looking for

  • 0
  neufuse said:
why would you need an array? if you add it to a container control such as a form or panel that control / form has a controls property which you can use to reference controls that have been added to the form / container... that would be the only case you'd want to specify a "name" for a control then you could do a string.compare to compare the name of the control and the item you are looking for

going on the code you demo'd, which is pretty much how i'm going about things...

I'm currently doing...

Adding tab pages to a Tab Control based on the number specified. Then for each tab I need to have the same grid drawn on them, which would be a series of textboxes.

Seen as I need a variable name for each control that is added, preferably an array seen as its a grid ;) how would I determine how many variables I need?

Probably going about this all wrong but whatever! :D

  • 0
  neufuse said:
If you dynamically create a control the "name" property means nothing... The Name property is for the IDE only and has no meaning at runtime

I'm not sure that I agree with you here.

The "Name" property is plenty valid at runtime, and I think that it's good programming practice to set it when you create a control

eg

Dim newctl As New System.Windows.Forms.TextBox

newctl.Location = New System.Drawing.Point(102, 9)

newctl.Name = "txtMyNewControl"

newctl.Size = New System.Drawing.Size(95, 20)

newctl.TabIndex = 9

Me.Controls.Add(newctl)

  neufuse said:
say you make a control like this

public class MyForm

Dim MyControl as new TextBox

public sub new

Me.Controls.Add(MyControl) ' add to form

with MyControl

.size = new size(21,100)

.Location = new Point(10,10)

end With

end sub

public sub UpdateControlsText

' Access the control now with the object you made in the class outside of a sub or function

MyControl.Text = "Text Here"

End Sub

end class

not that hard eh? anytime you make a control inside a sub though you need a reference to the control so you can access it outside that sub also!

True - but if you've named the control you can find it ;-)

The following function will "find" a control by name on a form, even if it's hiding inside a tab control...

Private Function FindControl(ByVal parent As Control, ByVal ident As String) As Control

Dim n As Integer

Dim tmpctrl As Control

Dim tmpctrl2 As Control

For n = 0 To parent.Controls.Count - 1

tmpctrl = parent.Controls(n)

If tmpctrl.Name = ident Then

Return parent.Controls(n)

ElseIf tmpctrl.Controls.Count > 0 Then

tmpctrl2 = FindControl(tmpctrl, ident)

If Not IsNothing(tmpctrl2) Then

Return tmpctrl2

End If

End If

Next

' Not found

Return Nothing

end function

You call it by sending "me" (ie the form) and the name of the control you want to manipulate.

  • 0
  MiG- said:
going on the code you demo'd, which is pretty much how i'm going about things...

I'm currently doing...

Adding tab pages to a Tab Control based on the number specified. Then for each tab I need to have the same grid drawn on them, which would be a series of textboxes.

Seen as I need a variable name for each control that is added, preferably an array seen as its a grid ;) how would I determine how many variables I need?

Probably going about this all wrong but whatever! :D

Well first of all, it sounds like what you really want is a custom UserControl that includes the appropriate TextBox grid. Then when you need to add a page, you add one of those to it, instead of manually adding all the text boxes each time. You can even build your custom control in the Forms Designer. And you can put simple methods / properties on it to handle any work it needs to do for you, or expose any data you need in the parent form.

If the parent form (code outside the UserControl) needs to access the text boxes, or they need to access each other, there are several ways to accomplish that. For example, you can maintain an array / list with references to all the custom controls you added. Or you can simply get to the custom control through the Tab control.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Raspberry Pi Imager 1.9.4 released bringing performance improvements, bug fixes and more by David Uzondu Raspberry Pi Imager 1.9.4 is now out, marking the first official release in its 1.9.x series. This application, for anyone new to it, is a tool from the Raspberry Pi Foundation. It first came out in March 2020. Its main job is to make getting an operating system onto a microSD card or USB drive for any Raspberry Pi computer super simple, even if you hate the command line. It handles downloading selected OS images and writing them correctly, cutting out several manual steps that used to trip people up, like finding the right image version or using complicated disk utility tools. This version brings solid user interface improvements for a smoother experience, involving internal tweaks that contribute to a more polished feel. Much work went into global accessibility, adding new Korean and Georgian translations. Updates also cover Chinese, German, Spanish, Italian, and many others. Naturally, a good number of bugs got squashed, including a fix for tricky long filename issues on Windows and an issue with the Escape key in the options popup. Changes specific to operating systems are also clear. Windows users get an installer using Inno Setup. Its program files, installer, and uninstaller are now signed for better Windows security. For macOS, .app file naming in .dmg packages is fixed, and building the software is more reliable. Linux users can now hide system drives from the destination list, a great way to prevent accidentally wiping your main computer drives. The Linux AppImage also disables Wayland support by default. The full list of changes is outlined below: Fixed minor errors in Simplified Chinese translation Updated translations for German, Catalan, Spanish, Slovak, Portuguese, Hebrew, Traditional Chinese, Italian, Korean, and Georgian Explicitly added --tree to lsblk to hide partitions from the top-level output CMake now displays the version as v1.9.1 Added support for quiet uninstallation on Windows Applied regex to match SSH public keys during OS customization Updated dependencies: libarchive (3.7.4 → 3.7.7 → 3.8.0) zlib (removed preconfigured header → updated to 1.4.1.1) cURL (8.8 → 8.11.0 → 8.13.0) nghttp2 (updated to 1.65.0) zstd (updated to 1.5.7) xz/liblzma (updated to 5.8.1) Windows-specific updates: Switched to Inno Setup for the installer Added code signing for binaries, installer, and uninstaller Enabled administrator privileges and NSIS removal support Fixed a bug causing incorrect saving of long filenames macOS-specific updates: Fixed .app naming in .dmg packages Improved build reliability and copyright Linux-specific updates: System drives are now hidden in destination popup Wayland support disabled in AppImage General UI/UX improvements: Fixed OptionsPopup not handling the Esc key Improved QML code structure, accessibility, and linting Made options popup modal Split main UI into component files Added a Style singleton and ImCloseButton component Internationalization (i18n): Made "Recommended" OS string translatable Made "gigabytes" translatable Packaging improvements: Custom AppImage build script with Qt detection Custom Qt build script with unprivileged mode Qt 6.9.0 included Dependencies migrated to FetchContent system Build system: CMake version bumped to 3.22 Various improvements and hardening applied Removed "Show password" checkbox in OS customization settings Reverted unneeded changes in long filename size calculation Internal refactoring and performance improvements in download and extract operations Added support for more archive formats via libarchive Lastly, it's worth noting that the system requirements have changed since version 1.9.0: macOS users will need version 11 or later; Windows users, Windows 10 or newer; Ubuntu users, version 22.04 or newer; and Debian users, Bookworm or later.
    • Ancient CD app makes 64-bit comeback to support Windows 11 and probably Windows 10 too by Sayan Sen Remember when CDs or compact discs were a thing? While technically, they still are, their popularity and usage have dropped immensely with the rise in other standards like USB, as the latter continues to evolve, getting faster and gaining more features. Recently, Microsoft enforced some mandatory requirements for USB Type-C so as to ensure a uniform and consistent experience for Windows 11 users. On the topic of Windows 11 and CDs, a CD ripping tool from the Windows 95/98 era, dubbed "CD2WAV32," is back again after 16 years (from the Windows 7 era). The utility has now been updated to work on Windows 11 version 24H2, which is pretty cool. This was not planned, says the author, as they simply wanted to test the app on their newly upgraded Windows 11 PC, but ended up going all the way to make it fully work on Windows 11. Their Windows 11 runs an AMD Ryzen 9600X, 64 GB RAM, and an Nvidia GT 1030 (miswritten as "GT1300"). The developer of the tool notes that they did not run thorough tests on Windows 10, but it works on their Atom-based PC, which is another relic, given how fast technology moves. The author writes (Google-translated from Japanese to English): "From now on, it will only support Windows 11 (24H2). The reason is that this is the only environment the author currently has. I haven't done anything particularly fancy, so I think it will work properly on Windows 10, but I can't guarantee it. All I have left is an ATOM machine that I bought a long time ago that also runs Windows 10, so I've seen that it works lightly on that, but I can't do a detailed test." Atom, for those wondering, was Intel's low-power CPU lineup that it decided to axe back in 2016. The story is similar to how Microsoft gave up on Windows Lumia, as Intel, too, abandoned its mobile chip ambitions once the likes of Qualcomm and MediaTek took over. In terms of the underlying changes, the utility has been compiled now on Delphi 12.1 Community Edition, which is used to make native Windows apps as well as ones for macOS, iOS, and Android. The recent update also brings a significant overhaul in terms of compatibility as well as UX/UI. File sizes and other such metadata are now handled using a 64-bit format instead of the prior 32-bit approach, eliminating overflow issues and ensuring large file and disk space values are displayed correctly. This change is necessary given that large storage volumes are quite common these days. Additionally, support for 16-bit code calling functions has been entirely removed as Windows 11 is 64-bit only; thus, features like MSCDEX and TwinVQ compression are gone. Meanwhile, the font has been changed from MSP Gothic 9pt to Meiryo 10pt, so readability should not be a problem even on 4K screens. In terms of audio file encoding support, it is said to work with MP3 as well as WMA. So, should you download and run it? Probably not, given that the UI is entirely Japanese, but it is still a fun project to look at.
    • Xbox has lots of games… and there all coming to Playstation!
    • Athena was the goddess of wisdom and war interesting choice
  • Recent Achievements

    • Week One Done
      jbatch earned a badge
      Week One Done
    • First Post
      Yianis earned a badge
      First Post
    • Rookie
      GTRoberts went up a rank
      Rookie
    • First Post
      James courage Tabla earned a badge
      First Post
    • Reacting Well
      James courage Tabla earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      397
    2. 2
      +FloatingFatMan
      177
    3. 3
      snowy owl
      170
    4. 4
      ATLien_0
      167
    5. 5
      Xenon
      134
  • Tell a friend

    Love Neowin? Tell a friend!