<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>dynamic Archive - Robert Skibbe</title>
	<atom:link href="https://robbelroot.de/blog/tag/dynamic/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>alias RobbelRoot – Freelance Full Stack Developer .NET</description>
	<lastBuildDate>Wed, 08 Apr 2026 21:54:18 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://robbelroot.de/wp-content/uploads/2020/12/cropped-favicon-32x32.png</url>
	<title>dynamic Archive - Robert Skibbe</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to access Controls dynamically in .NET (Winforms &#038; WPF)</title>
		<link>https://robbelroot.de/blog/how-to-access-controls-dynamically-in-net-csharp-and-vbnet/</link>
					<comments>https://robbelroot.de/blog/how-to-access-controls-dynamically-in-net-csharp-and-vbnet/#respond</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Sat, 04 Nov 2023 07:34:53 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C# HowTo's]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Visual Basic .NET (EN)]]></category>
		<category><![CDATA[access]]></category>
		<category><![CDATA[child]]></category>
		<category><![CDATA[children]]></category>
		<category><![CDATA[controls]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[dynamically]]></category>
		<category><![CDATA[element]]></category>
		<category><![CDATA[elements]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[forms]]></category>
		<category><![CDATA[iterate]]></category>
		<category><![CDATA[iterating]]></category>
		<category><![CDATA[vbnet]]></category>
		<category><![CDATA[visuals]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[winforms]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=17717</guid>

					<description><![CDATA[<p>In short: You can access controls in .NET dynamically, by using the &#8222;Controls&#8220; property of your parent container control, like for example a &#8222;Form&#8220; in Winforms. However, if you&#8217;re using WPF, you will need a small helper function / the VisualTreeHelper to access the controls dynamically. Keep in mind, that &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/how-to-access-controls-dynamically-in-net-csharp-and-vbnet/">How to access Controls dynamically in .NET (Winforms &#038; WPF)</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2023/11/How-to-access-Controls-dynamically-in-.NET-for-csharp-and-visual-basic.png"><img fetchpriority="high" decoding="async" width="659" height="371" src="https://robbelroot.de/wp-content/uploads/2023/11/How-to-access-Controls-dynamically-in-.NET-for-csharp-and-visual-basic.png" alt="How to access Controls dynamically in .NET - for csharp and visual basic" class="wp-image-17725" title="How to access Controls dynamically in .NET - for csharp and visual basic"/></a><figcaption class="wp-element-caption">How to access Controls dynamically in .NET &#8211; for csharp and visual basic</figcaption></figure>



<p class="answer-paragraph"><strong>In short: You can access controls in .NET dynamically, by using the &#8222;Controls&#8220; property of your parent container control, like for example a &#8222;Form&#8220; in Winforms. However, if you&#8217;re using WPF, you will need a small helper function / the VisualTreeHelper to access the controls dynamically. Keep in mind, that you should consider using the MVVM pattern with WPF.</strong></p>






<h2 class="wp-block-heading">Accessing form (container) controls dynamically</h2>



<p>If you&#8217;ve ever asked yourself like &#8222;How do I actually access controls on the form dynamically&#8220;, then today&#8217;s blog post is for you! To get you completely covered, we will not only look at the oldschool / typical Windows Forms stuff (Winforms), but at the Windows Presentation Foundation (WPF), as well. It doesn&#8217;t really matter, if you&#8217;re having those controls ready at startup, or if you&#8217;re creating them dynamically at runtime – I will be covering both aspects.</p>


<p class="rr-alert info" style="background:#e3f7fc;"><img decoding="async" alt="Info notice" src="https://robbelroot.de/wp-content/themes/pinboard-child/imgs/info.png"><span style="color:black;align-self: center;">Click <a href="#iterating-number-based">here</a> to jump straight to the easiest example – being a numbering based approach of dynamic control access. <a href="#quick-examples">Here</a> you can find the quick examples without blabla – if you&#8217;re like in a hurry. Feel free, to use the <a href="#toc_container">table of contents</a> from above, to navigate yourself through this blogpost.</span></p>



<h2 class="wp-block-heading">A problem with containers</h2>



<p>Before we dive deeper into the &#8222;how and what&#8220;, I want to clear up some things first. Even though I first planned to &#8222;spoiler&#8220; it here and there in the bottom sections, I decided to make it extra clear, beforehand. I&#8217;m talking about the problems you will face, if you have your target controls in different &#8222;container controls&#8220;.</p>



<p>Think for example about the soon following screenshot. You will see different panels being / representing &#8222;container&#8220; controls – determined, to only represent some sort of: &#8222;I will have children aligned inside myself&#8220;. I mean, every Control inheriting from the base class can have Sub-Controls, but things like Panels or for example a GroupBox are really designed for that.</p>



<p>This is the reason why we have an extra group for that inside of the ToolBox, right?</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2023/11/Container-controls-inside-of-the-Visual-Studio-Designer-ToolBox.png"><img decoding="async" width="310" height="458" src="https://robbelroot.de/wp-content/uploads/2023/11/Container-controls-inside-of-the-Visual-Studio-Designer-ToolBox.png" alt="Container controls inside of the Visual Studio Designer ToolBox" class="wp-image-17895" title="Container controls inside of the Visual Studio Designer ToolBox"/></a><figcaption class="wp-element-caption">Container controls inside of the Visual Studio Designer ToolBox</figcaption></figure>



<p>Now if you take a look at the example screenshot below, you will see <strong>3 Panels having child-controls</strong> inside of them. It could be pretty obvious, that <strong>if you&#8217;re using &#8222;Me.Controls&#8220; or just &#8222;Controls&#8220;</strong> inside of your form code, <strong>you won&#8217;t be getting one of those buttons or labels</strong>. <strong>You will get the direct children of the form – being the Panels!</strong> But as obvious as this sounds, this is one of the most popular problems, beginners will face.</p>



<p>You would potentially be better off using some sort of own / custom storage for: &#8222;Here are my controls I want to iterate later&#8220;. I explained this approach further down, inside of the <strong><a href="#Using-a-list-to-track-the-target-controls">&#8222;using a custom list, etc. to track target elements&#8220;-section</a></strong>.</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2023/11/Parent-Form-with-different-Panels-on-it-being-containers.png"><img decoding="async" width="600" height="489" src="https://robbelroot.de/wp-content/uploads/2023/11/Parent-Form-with-different-Panels-on-it-being-containers.png" alt="Parent Form with different Panels on it being containers" class="wp-image-17893" title="Parent Form with different Panels on it being containers"/></a><figcaption class="wp-element-caption">Parent Form with different Panels on it being containers</figcaption></figure>



<h2 class="wp-block-heading" id="winforms-example">Winforms – dynamically accessing controls</h2>



<p>In this first section we will talk about one of the most basic tasks a .NET developer can face. Especially if your&#8217;re just starting with .NET and you&#8220;ll&#8217;re like beginning with Windows Forms. Imagine, that you&#8217;re having a basic form (from the <strong><a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form" target="_blank" rel="noreferrer noopener">&#8222;System.Windows.Forms&#8220; namepace</a></strong>) with some buttons. Now it would be great, if you could speed up your coding with like &#8222;Hey, I want to access all of those buttons and I don&#8217;t want to access them one after another – manually&#8220;.</p>



<p>If you&#8217;re looking for a <strong><a href="#wpf-example">more modern WPF example</a></strong>, just scroll down or click the link.</p>



<h3 class="wp-block-heading">An example UI as a base</h3>



<p>The form could for example look like the following. I just made up a simple example of some sort of &#8222;here&#8217;s a menu and if cou click a button, you&#8217;ll switch to that specific view&#8220; UI:</p>



<figure class="wp-block-image size-full" id="left-side-menu-items-screenshot"><a href="https://robbelroot.de/wp-content/uploads/2023/11/An-example-menu-and-sub-view-app-accessing-Controls-dynamically-in-.NET_.png"><img loading="lazy" decoding="async" width="804" height="488" src="https://robbelroot.de/wp-content/uploads/2023/11/An-example-menu-and-sub-view-app-accessing-Controls-dynamically-in-.NET_.png" alt="An example menu and sub-view app - accessing Controls dynamically in .NET" class="wp-image-17747" title="An example menu and sub-view app - accessing Controls dynamically in .NET"/></a><figcaption class="wp-element-caption">An example menu and sub-view app &#8211; accessing Controls dynamically in .NET</figcaption></figure>



<p>Seeing this basic menuing example from above, you could now have the goal, to dynamically access these buttons. I&#8217;m talking for example about some sort of authentication / authorization based decisions. A person working inside of the bill related departments should for example only be seeing / be able to navigate to the relevant menu items.</p>



<p>Contrary to the bill related department, an apprentice should potentially be drastically limited in his navigation possibilities. You would therefore try to avoid all irrelevant or unallowed menu items by like hiding or disabling them. And at last, an admin should most likely be able to access and view everything.</p>



<p>The problem now arises, that you would have to repeat code again and again, for each role or permission. This would lead to a huge amount of lines written by hand. The good news is, that there are easier ways, but let&#8217;s first look at how it probably shouldn&#8217;t be done.</p>



<h3 class="wp-block-heading">A &#8222;wrong&#8220; way and the inherent problems</h3>



<p>An experienced developer would – of course – try to avoid some sort of repetitive code like the following, when approaching a possible solution. In this code we approach each button on his own by calling him by his name and (in the worst case) like hardcoding the values in the end.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="repetitive-menu-hiding">//repetitive, meh - bad code!
btnMenuDashboard.Visible = ...;
btnMenuCustomers.Visible = ...;
btnMenuBills.Visible = ...;
btnMenuCalendar.Visible = ...;
btnMenuSettings.Visible = ...;
btnMenuAbout.Visible = ...;

// and it even grows / needs to be adjusted,
// when more menu items come into play
// or get removed
// ...</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="repetitive-menu-hiding">'repetitive, meh - bad code!
btnMenuDashboard.Visible = ...
btnMenuCustomers.Visible = ...
btnMenuBills.Visible = ...
btnMenuCalendar.Visible = ...
btnMenuSettings.Visible = ...
btnMenuAbout.Visible = ...

' and it even grows / needs to be adjusted,
' when more menu items come into play
' or get removed
' ...</pre>



<p>Many developers – especially beginners or non-professionals – will of course use anything that &#8222;just works&#8220;. In the end, you need to ask yourself, what your personal approach on creating solutions is. When thinking about these kind of decisions, you should always think about some things first.</p>



<p>These <strong>considerations </strong>could be:</p>



<ul class="wp-block-list">
<li>Will I be <strong>able to extend and maintain</strong> the code I wrote in the future?</li>



<li>Even more important – <strong>will someone else </strong>be?</li>



<li>Is the <strong>code </strong>actually<strong> efficient</strong>?</li>



<li>Does the code <strong>have a good portability</strong> / reusability?</li>



<li>How does it look considering the maintainability?</li>
</ul>



<p>Let&#8217;s talk about one possible and potentially better approach of the above code example in the next step.</p>



<h3 class="wp-block-heading">A better way – dynamic access of controls by their names</h3>



<p>Please keep in mind, that the suggestions I will provide, are only suggestions. There&#8217;s no &#8222;100% way&#8220;, as you need to balance for yourself, what key consideration is getting what kind of weight. In the end, I&#8217;m just talking about different aspects and their advantages / disadvantages – your personal conclusion is obviously your responsibility.</p>



<p>I&#8217;m talking about things like:</p>



<ul class="wp-block-list">
<li>Do you develop these things for yourself, maybe as like a hobby?</li>



<li>Are you going to use the code in professional environments?</li>



<li>Does a customer like limit you considering budget &amp; time?</li>



<li>Are you working together inside of a team?</li>
</ul>



<h3 class="wp-block-heading">The key takeaway of dynamic control access</h3>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2023/11/Dynamic-control-access-through-the-containers-Controls-property.png"><img loading="lazy" decoding="async" width="659" height="371" src="https://robbelroot.de/wp-content/uploads/2023/11/Dynamic-control-access-through-the-containers-Controls-property.png" alt="Dynamic control access through the containers Controls property" class="wp-image-17802" title="Dynamic control access through the containers Controls property"/></a><figcaption class="wp-element-caption">Dynamic control access through the containers Controls property</figcaption></figure>



<p>Before we start with the actual dynamic access, let&#8217;s strengthen the overall understanding behind &#8222;controls&#8220; in general. I think, that you can agree on the fact, that controls will appear with different purposes. The most important takeaway when talking about the dynamic access, is the <strong><a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.controls">&#8222;Controls&#8220;-Property</a></strong>.</p>



<p>This property exists, because every control (inheriting from the corresponding base class) can actually contain multiple sub-controls as well. Great! This is actually where we can build our dynamic access up upon. I mean, at least considering that property!</p>


<p class="rr-alert warning" style="background:#fff8c4;"><img decoding="async" alt="Warning notice" src="https://robbelroot.de/wp-content/themes/pinboard-child/imgs/warning.png"><span style="color:black;align-self: center;">Take care, that you&#8217;re actually accessing the Controls-property for the right control! If you&#8217;re accessing the forms Controls property, but the controls are actually inside another panel, it won&#8217;t work!</span></p>



<h4 class="wp-block-heading">Iterating using a typical index</h4>



<p>To be complete, I will include this example as well, but I think it&#8217;s the most obvious way, at least when knowing about the &#8222;Controls&#8220; property. I&#8217;m talking about the typical approach, which you&#8217;re potentially already aware about – an access by index.</p>



<p>Take a look at typical &#8222;list&#8220; based stuff, like the &#8222;List&#8220; class, arrays and more. I will use a list for an example here and demonstrate the typical index based access of elements:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="iterating-typical-index">// initialize a list to have some data
List&lt;int> someNumbers = new List&lt;int>()
{
  11, 22, 33
};

// now access the specific data
// get for example the second value
// being a 22
int secondValue = someNumbers[1];</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="iterating-typical-index">' initialize a list to have some data
Dim someNumbers = New List(Of Integer)() From
{
  11, 22, 33
}

' now access the specific data
' get for example the second value
' being a 22
Dim secondValue As Integer = someNumbers(1)</pre>



<p>I&#8217;m sure that you already know that, but as mentioned – I want to be totally complete. In the next step, you can do pretty much the same for dynamically accessing controls from your form / window. You just need to access the correct property of the form. (Please take the above warning text into consideration – make sure, that you target the &#8222;Controls&#8220; property of the correct parent element).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="controls-prop-with-index">// iterate each control of the
// target "Controls" property
for (int i = 0; i &lt; Controls.Count; i++)
{
    // get a reference to the control
    // at the specified index
    Control control = Controls[i];
    // do something with the control
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="controls-prop-with-index">' iterate each control of the
' target "Controls" property
For i As Integer = 0 To Controls.Count - 1
    ' get a reference to the control
    ' at the specified index
    Dim ctl As Control = Controls(i)
    ' do something with the ctl
Next</pre>



<h4 class="wp-block-heading" id="iterating-number-based">Iterating numbering based names</h4>



<p>I think, that <strong>one</strong> of the most <strong>common </strong>approaches of dynamic control access in for example Windows Forms, is by using some sort of numbering. This means you could <strong>incrementally name your button controls</strong> like the following. Please keep in mind, that you should always choose descriptional / good names and that this is only for explanational purposes:</p>



<p>Let&#8217;s for example take this (potentially) new acquired knowledge to our first example. I will iterate 3 buttons within a specific – I will call it – &#8222;container control&#8220;. Further, you need to know, that you can use an indexer when using the mentioned &#8222;Controls&#8220; property. But not only an integer, you can actually use a key / an index represented by a string, as well:</p>



<p>The buttons could be named like:</p>



<ul class="wp-block-list">
<li>Button1</li>



<li>Button2</li>



<li>Button3</li>
</ul>



<p>You can <strong>now iterate over each button</strong> to change the background color like the following snippet. Keep in mind, that <strong>I&#8217;m using a &#8222;nullable of button&#8220; typed declaration</strong>. This is because you <strong>could try to get a control (by name) which doesn&#8217;t actually exist</strong>! This is exactly why we&#8217;re <strong>checking for &#8222;null&#8220;</strong> / &#8222;nothing&#8220; with the if statement, but there&#8217;s more! With this kind of &#8222;is&#8220; expression, we&#8217;ve <strong>already casted the button</strong> to a usable type, as well.</p>



<p>Take care, that I <strong>personally prefer the string interpolation syntax</strong> using the dollar sign and that curly braces syntax sugar. The code for VB.NET is slightly different, but in it&#8217;s core, we&#8217;re doing pretty much the same stuff.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="first-numbered-iteration">// iterate 3 times, because we
// have 3 buttons in this example
for (var i = 1; i &lt;= 3; i++)
{
    // get a (potential!) reference
    // to the button
    Control? btn = Controls[$"Button{i}"];
    // check if the received control is
    // not empty and actually a button
    if (btn is Button)
    {
        // use the typed button instance
        btn.BackColor = Color.IndianRed;
    }
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="first-numbered-iteration">' iterate 3 times, because we
' have 3 buttons in this example
For i = 1 To 3
    ' get a (potential!) reference
    ' to the button
    Dim btn As Control? = Controls($"Button{i}")
    ' check if the received control is
    ' not empty and actually a button
    If TypeOf btn Is Button Then
        ' use the typed button instance
        btn.BackColor = Color.IndianRed
    End If
Next</pre>



<h4 class="wp-block-heading">Using a list to track the target controls</h4>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2023/11/Creating-a-custom-store-to-dynamically-iterate-controls.png"><img loading="lazy" decoding="async" width="659" height="371" src="https://robbelroot.de/wp-content/uploads/2023/11/Creating-a-custom-store-to-dynamically-iterate-controls.png" alt="Creating a custom store to dynamically iterate controls" class="wp-image-17822" title="Creating a custom store to dynamically iterate controls"/></a><figcaption class="wp-element-caption">Creating a custom store to dynamically iterate controls</figcaption></figure>



<p>After we&#8217;ve seen the most typical approach in the last section. We can now look at another example for iterating some controls. It could for example be, that a number based strategy doesn&#8217;t really work. That means, that it&#8217;s potentially not applicable, to use something like &#8222;XyzControl&lt;Number&gt;&#8220;.</p>



<p>If you think about <strong><a href="#left-side-menu-items-screenshot">the UI screenshot from above</a></strong>, my button controls were named like this:</p>



<ul class="wp-block-list">
<li>btnMenuDashboard</li>



<li>btnMenuCustomers</li>



<li>btnMenuBills</li>



<li>btnMenuCalendar</li>



<li>btnMenuSettings</li>



<li>btnMenuAbout</li>
</ul>



<p>As you can see, number based names wouldn&#8217;t make much sense here. But no problem, we can just use another approach. We will just create a custom &#8222;store&#8220; of &#8222;these are the buttons, that we are interested in&#8220; – resulting in for example a list, array or similar.</p>



<p>So let&#8217;s now group the buttons in some meaningful list and use that for the dynamic access of controls. With this approach, it doesn&#8217;t really matter, where the buttons reside in or where they are coming from. They could for example be in different parent controls, which is an important aspect. Keep in mind though, that you need to take care for the generic type of the List.</p>


<p class="rr-alert info" style="background:#e3f7fc;"><img decoding="async" alt="Info notice" src="https://robbelroot.de/wp-content/themes/pinboard-child/imgs/info.png"><span style="color:black;align-self: center;">You probably need to adjust the generic type parameter of the list according to your needs. As I&#8217;m only interested in changing the &#8222;BackColor&#8220; property, I can easily use the base class <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control" target="_blank" rel="noopener">&#8222;Control&#8220;</a> – instead of for example the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.button" target="_blank" rel="noopener">&#8222;Button&#8220;</a> class.</span></p>



<p> </p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="custom-store-as-base">public partial class Form1 : Form
{

    // create a "backing" store for the buttons
    // adjust accessibility depending on your needs
    // like maybe exposing as readonly property
    private List&lt;Control> _menuButtons;

    public Form1()
    {
        InitializeComponent();

        // initializing the list making it usable
        // and avoiding a null-reference
        _menuButtons = new List&lt;Control>()
        {
            btnMenuDashboard,
            btnMenuCustomers,
            btnMenuBills,
            btnMenuCalendar,
            btnMenuSettings,
            btnMenuAbout,
        };

        // attach the handler to each button
        foreach (Control ctl in _menuButtons)
            ctl.Click += MenuButton_Clicked;
    }

    // work with the list later on
    private void MenuButton_Clicked(object? sender, EventArgs e)
    {
      Control? ctl = sender As Control;
      if (ctl == null)
        return;
      ctl.BackColor = Color.IndianRed;
    }

}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="custom-store-as-base">Public Partial Class Form1
    Inherits Form

    ' create a "backing" store for the buttons
    ' adjust accessibility depending on your needs
    ' like maybe exposing as readonly property
    Private _menuButtons As List(Of Control)

    Public Sub New()
        InitializeComponent()

        ' initializing the list making it usable
        ' and avoiding a null-reference
        _menuButtons = New List(Of Control)() From {
            btnMenuDashboard,
            btnMenuCustomers,
            btnMenuBills,
            btnMenuCalendar,
            btnMenuSettings,
            btnMenuAbout
        }

        ' attach the handler to each button
        For Each ctl In _menuButtons
            AddHandler ctl.Click, AddressOf MenuButton_Clicked
        Next
    End Sub

    Private Sub MenuButton_Clicked(sender As Object, e As EventArgs)
        If sender Is Nothing Then
            Return
        End If
        Dim ctl = CType(sender, Control)
        ctl.BackColor = Color.IndianRed
    End Sub

End Class</pre>



<h2 class="wp-block-heading" id="wpf-example">WPF – accessing controls dynamically</h2>



<p>In the next section, we will talk about the WPF relevant part. If you&#8217;re looking for the <strong><a href="#winforms-example">Windows Forms based example</a></strong>, just click the link or scroll up a bit. Please keep in mind, that WPF is mostly a different story, because it&#8217;s a primarily MVVM oriented core approach.</p>



<p>I won&#8217;t be talking about the MVVM pattern over here, as the post is already big enough, I think. Feel free to visit the separate <strong><a href="https://robbelroot.de/blog/mvvm-csharp/">blogpost regarding the MVVM pattern</a></strong>, if you need more information. I will just go this far at this point: Usually – when using the Windows Presentation Foundation – you will be using data as source for like everything.</p>



<p>The so called views, will be represented by some sort of matching viewmodel which contains the data (and sub-viewmodels) needed to do so. Therefore you will mostly not be facing the &#8222;dynamic control access&#8220; problem as like in Windows Forms.</p>



<p>However, if you do so, you can go for a UI first targeted approach like the following. Keep in mind, that I provided some sort of helper function, to get the <strong><a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.frameworkelement" target="_blank" rel="noreferrer noopener">FrameworkElements</a></strong> (or <strong><a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.visual">Visuals</a></strong>) from the actual view.</p>



<h3 class="wp-block-heading">Helper method to get all controls of a control</h3>



<p>Take a look at the following static helper method (defined in a separate, static class), which can pull the sub-views and their descendants:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="wpf-helper-getchildren">using System.Collections.Generic;
using System.Windows.Media;

namespace WpfExampleCs;

public static class Helper
{

    public static IEnumerable&lt;Visual> GetChildren(this Visual parent, bool recursive = true)
    {
        // throw an exception?
        if (parent == null)
            yield break;

        int count = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i &lt; count; i++)
        {
            // get child reference by index
            Visual? child = VisualTreeHelper.GetChild(parent, i) as Visual;
            if (child == null)
                continue;

            // we've found one item
            yield return child;

            // don't go deeper
            if (!recursive)
                continue;

            // check for further descendants as well
            foreach (var grandChild in child.GetChildren(recursive))
                yield return grandChild;
        }
    }

}
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="wpf-helper-getchildren">Imports System.Collections.Generic
Imports System.Windows.Media
Imports System.Runtime.CompilerServices

Namespace WpfExampleCs
    Module Helper
        &lt;Extension()>
        Iterator Function GetChildren(ByVal parent As Visual, ByVal Optional recursive As Boolean = True) As IEnumerable(Of Visual)
            If parent Is Nothing Then Return
            Dim count As Integer = VisualTreeHelper.GetChildrenCount(parent)

            For i As Integer = 0 To count - 1
                Dim child As Visual? = TryCast(VisualTreeHelper.GetChild(parent, i), Visual)
                If child Is Nothing Then Continue For
                Yield child
                If Not recursive Then Continue For

                For Each grandChild In child.GetChildren(recursive)
                    Yield grandChild
                Next
            Next
        End Function
    End Module
End Namespace
</pre>



<p>You can then call and use the method similar to the iteration of <strong><a href="#Iterating-using-a-typical-index">the windows forms controls example from above</a></strong>. Adjust the code for example by striping away that &#8222;recursive&#8220; stuff, to only go like linear – being direct children of the provided parent / target.</p>


<p class="rr-alert warning" style="background:#fff8c4;"><img decoding="async" alt="Warning notice" src="https://robbelroot.de/wp-content/themes/pinboard-child/imgs/warning.png"><span style="color:black;align-self: center;">Be careful, that this can imply performance problems, if you&#8217;re using like many levels of control-nesting. Try to optimize the code for your usecase, if possible!</span></p>



<h3 class="wp-block-heading">Only get controls matching a predicate</h3>



<p>You could for example adjust the above function, to only pull some controls at startup of the program, using a specific predicate (criteria):</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="wpf-controls-matching-predicate">using System;
using System.Collections.Generic;
using System.Windows.Media;

namespace WpfExampleCs;

public static class Helper
{

    public static IEnumerable&lt;Visual> GetChildren(this Visual parent, bool recursive = true, Predicate&lt;Visual> predicate)
    {
        // throw an exception?
        if (parent == null)
            yield break;

        int count = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i &lt; count; i++)
        {
            // get child reference by index
            Visual? child = VisualTreeHelper.GetChild(parent, i) as Visual;
            if (child == null)
                continue;

            // we've found one item
            if (predicate(child))
                yield return child;

            // don't go deeper
            if (!recursive)
                continue;

            // check for further descendants as well
            foreach (var grandChild in child.GetChildren(recursive, predicate))
            {
                if (predicate(grandChild))
                    yield return grandChild;
            }
        }
    }

}
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="wpf-controls-matching-predicate">Imports System
Imports System.Collections.Generic
Imports System.Windows.Media
Imports System.Runtime.CompilerServices

Namespace WpfExampleCs
    Module Helper
        &lt;Extension()>
        Iterator Function GetChildren(ByVal parent As Visual, ByVal Optional recursive As Boolean = True, ByVal predicate As Predicate(Of Visual)) As IEnumerable(Of Visual)
            If parent Is Nothing Then Return
            Dim count As Integer = VisualTreeHelper.GetChildrenCount(parent)

            For i As Integer = 0 To count - 1
                Dim child As Visual? = TryCast(VisualTreeHelper.GetChild(parent, i), Visual)
                If child Is Nothing Then Continue For
                If predicate(child) Then Yield child
                If Not recursive Then Continue For

                For Each grandChild In child.GetChildren(recursive, predicate)
                    If predicate(grandChild) Then Yield grandChild
                Next
            Next
        End Function
    End Module
End Namespace
</pre>



<p>Usage could then look like:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="wpf-controls-matching-predicate-usage">// usage for example in the MainWindow class
// within like a button
string thePrefix = "Button_";
IEnumerable&lt;Visual> allVisualsStartingWithPrefix = this.GetChildren(true, x => x.Name.StartsWith(thePrefix));</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="wpf-controls-matching-predicate-usage">' usage for example in the MainWindow class
' within like a button
Dim thePrefix As String = "Button_"
    Dim allVisualsStartingWithPrefix As IEnumerable(Of Visual) = Me.GetChildren(True, Function(x) x.Name.StartsWith(thePrefix))</pre>



<h2 class="wp-block-heading">Quick examples</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2023/11/Quick-Examples-of-dynamic-control-access-in-dotnet.png"><img loading="lazy" decoding="async" width="659" height="371" src="https://robbelroot.de/wp-content/uploads/2023/11/Quick-Examples-of-dynamic-control-access-in-dotnet.png" alt="Quick Examples of dynamic control access in .NET" class="wp-image-17842" title="Quick Examples of dynamic control access in .NET"/></a><figcaption class="wp-element-caption">Quick Examples of dynamic control access in .NET</figcaption></figure>



<p>If you&#8217;re just looking for some copy &amp; paste ready examples, here&#8217;s the section to go. Keep in mind, that I won&#8217;t repeat the details from above sections, so you only see the examples without the detailed explanations around them.</p>



<h3 class="wp-block-heading">For Windows Forms</h3>



<h4 class="wp-block-heading">Iterating form controls by index</h4>



<p>Using this code, you can for example iterate the forms controls using a typical index approach. More details on this <strong><a href="#Iterating-using-a-typical-index">are found here</a></strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="quick-example-typical-index">for (int i = 0; i &lt; Controls.Count; i++)
{
    Control control = Controls[i];
    // do something with the control
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="quick-example-typical-index">For i As Integer = 0 To Controls.Count - 1
    Dim ctl As Control = Controls(i)
    ' do something with the control
Next</pre>



<h4 class="wp-block-heading">Access controls based on numbered names</h4>



<p>Use this code inside of your for example forms button handler. It will access the &#8222;Controls&#8220; property of the form, where the buttons reside. Works for panels and even normal controls, alike, as every &#8222;Control&#8220; has a &#8222;Controls&#8220; property. Read more in <strong><a href="#Iterating-numbering-based">the detailed section</a></strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="quick-examples-numb-iterate">for (var i = 1; i &lt;= 3; i++)
{
    Control? btn = Controls[$"Button{i}"];
    if (btn is Button)
        btn.BackColor = Color.IndianRed;
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="quick-examples-numb-iterate">For i = 1 To 3
    Dim btn As Control? = Controls($"Button{i}")
    If TypeOf btn Is Button Then
        btn.BackColor = Color.IndianRed
    End If
Next</pre>



<h4 class="wp-block-heading">With a custom store as source</h4>



<p>Create a list, to remember the buttons you want to access and access them by iterating over the list afterwards. <strong><a href="#Using-a-list-to-track-the-target-controls">The more detailed description</a></strong> is further above in this blogpost.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="quick-examples-custom-store">public partial class Form1 : Form
{

    private List&lt;Control> _menuButtons;

    public Form1()
    {
        InitializeComponent();

        _menuButtons = new List&lt;Control>()
        {
            btnMenuDashboard,
            btnMenuCustomers,
            btnMenuBills,
            btnMenuCalendar,
            btnMenuSettings,
            btnMenuAbout,
        };

        foreach (Control ctl in _menuButtons)
            ctl.Click += MenuButton_Clicked;
    }

    private void MenuButton_Clicked(object? sender, EventArgs e)
    {
      Control? ctl = sender As Control;
      if (ctl == null)
        return;
      ctl.BackColor = Color.IndianRed;
    }

}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="quick-examples-custom-store">Public Partial Class Form1
    Inherits Form

    Private _menuButtons As List(Of Control)

    Public Sub New()
        InitializeComponent()

        _menuButtons = New List(Of Control)() From {
            btnMenuDashboard,
            btnMenuCustomers,
            btnMenuBills,
            btnMenuCalendar,
            btnMenuSettings,
            btnMenuAbout
        }

        For Each ctl In _menuButtons
            AddHandler ctl.Click, AddressOf MenuButton_Clicked
        Next
    End Sub

    Private Sub MenuButton_Clicked(sender As Object, e As EventArgs)
        If sender Is Nothing Then
            Return
        End If
        Dim ctl = CType(sender, Control)
        ctl.BackColor = Color.IndianRed
    End Sub

End Class</pre>



<h2 class="wp-block-heading">Wrapping up</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2023/11/Summary-wrapping-up-this-post.png"><img loading="lazy" decoding="async" width="659" height="371" src="https://robbelroot.de/wp-content/uploads/2023/11/Summary-wrapping-up-this-post.png" alt="Summary – Dynamically accessing controls" class="wp-image-17934" title="Summary – Dynamically accessing controls"/></a><figcaption class="wp-element-caption">Summary – Dynamically accessing controls</figcaption></figure>



<p>In today&#8217;s blogpost we talked about the different approaches of dynamic access to the forms or windows controls. We learned, that the approach will slightly depend on our used technology – primarily being either &#8222;Windows Forms&#8220; (Winforms) or &#8222;Windows Presentation Foundation&#8220; (WPF).</p>



<p>Especially if you&#8217;re using WPF, you need to take considerations like MVVM and the corresponding ViewModels into account. In the end, there are many similarities with the mentioned approaches being index, name or &#8222;custom store&#8220; based.</p>



<h2 class="wp-block-heading">Related posts</h2>



<p>Here you can find some blogposts you could potentially be interested in as well.</p>



<ul class="wp-block-list">
<li><strong><a href="https://robbelroot.de/blog/the-vb-net-for-loop-how-to-use-it-with-tips-tricks/">The VB.NET For Loop and some tips &amp; tricks</a></strong></li>



<li><strong><a href="https://robbelroot.de/blog/listing-the-applications-open-forms-in-winforms-and-wpf-apps/">Listing open forms / windows in .NET</a></strong></li>



<li><strong><a href="https://robbelroot.de/blog/the-csharp-this-keyword-what-is-it-how-to-use-it/">The &#8222;this&#8220; keyword in C#</a></strong></li>
</ul>
<p>Der Beitrag <a href="https://robbelroot.de/blog/how-to-access-controls-dynamically-in-net-csharp-and-vbnet/">How to access Controls dynamically in .NET (Winforms &#038; WPF)</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/how-to-access-controls-dynamically-in-net-csharp-and-vbnet/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>VB.NET AddHandler – Events dynamisch verknüpfen (2026)</title>
		<link>https://robbelroot.de/blog/vbnet-addhandler/</link>
					<comments>https://robbelroot.de/blog/vbnet-addhandler/#respond</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Sun, 11 Jul 2021 15:44:14 +0000</pubDate>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Visual Basic .NET]]></category>
		<category><![CDATA[add]]></category>
		<category><![CDATA[addhandler]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[dynamisch]]></category>
		<category><![CDATA[ereignis]]></category>
		<category><![CDATA[ereignishandler]]></category>
		<category><![CDATA[ereignisse]]></category>
		<category><![CDATA[event]]></category>
		<category><![CDATA[eventhandler]]></category>
		<category><![CDATA[executing]]></category>
		<category><![CDATA[handler]]></category>
		<category><![CDATA[laufen]]></category>
		<category><![CDATA[laufzeit]]></category>
		<category><![CDATA[runtime]]></category>
		<category><![CDATA[vb.net]]></category>
		<category><![CDATA[vbnet]]></category>
		<category><![CDATA[verknüpfen]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=3535</guid>

					<description><![CDATA[<p>Mit der VB.NET AddHandler-Anweisung verknüpfst du Ereignisse zur Laufzeit mit einer Methode, statt sie fest per Handles-Klausel im Code zu verdrahten. Das ist unverzichtbar, wenn du Controls dynamisch erstellst oder Ereignisse erst nach bestimmten Bedingungen zuweisen willst. Dieser Guide behandelt die Syntax, den Unterschied zu Handles, dynamische Controls, RemoveHandler, eigene &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vbnet-addhandler/">VB.NET AddHandler – Events dynamisch verknüpfen (2026)</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Mit der <strong>VB.NET AddHandler</strong>-Anweisung verknüpfst du Ereignisse zur Laufzeit mit einer Methode, statt sie fest per <code>Handles</code>-Klausel im Code zu verdrahten. Das ist unverzichtbar, wenn du Controls dynamisch erstellst oder Ereignisse erst nach bestimmten Bedingungen zuweisen willst. Dieser Guide behandelt die Syntax, den Unterschied zu <code>Handles</code>, dynamische Controls, <code>RemoveHandler</code>, eigene Events und gängige Fehler.</p>


<div style="box-sizing:border-box;margin:36px 0;border-radius:12px;overflow:hidden;background:#1a1a2e;position:relative;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
  <div style="position:absolute;inset:0;background-image:linear-gradient(rgba(255,255,255,0.03) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,0.03) 1px,transparent 1px);background-size:40px 40px;pointer-events:none;"></div>
  <div style="position:absolute;top:-60px;right:-60px;width:240px;height:240px;background:radial-gradient(circle,rgba(230,126,34,0.18) 0%,transparent 70%);pointer-events:none;"></div>
  <div style="position:relative;padding:32px 28px;">

        <div style="display:inline-block;font-size:11px;font-weight:700;letter-spacing:2.5px;text-transform:uppercase;color:#e67e22;margin-bottom:14px;border:1px solid rgba(230,126,34,0.35);border-radius:4px;padding:3px 10px;">.NET-Hilfe gesucht?</div>
    
        <p style="margin:0 0 10px 0;font-size:clamp(17px,4vw,21px);font-weight:700;color:#ffffff;line-height:1.35;">Du baust eine Desktop-Anwendung?</p>
    
        <p style="margin:0 0 24px 0;font-size:14px;color:rgba(255,255,255,0.65);line-height:1.7;max-width:540px;">Ich entwickle seit über 17 Jahren professionell in VB.NET und C#. Von Event-Handling bis zur kompletten WinForms-Anwendung kann ich helfen.</p>
    
    <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:center;">

            <a href="https://robbelroot.de/kontakt/"
         style="display:inline-block;padding:12px 24px;background:#e67e22;color:#ffffff;font-size:14px;font-weight:700;text-decoration:none;border-radius:7px;letter-spacing:0.3px;transition:background .2s ease;white-space:nowrap;"
         onmouseover="this.style.background='#cf6d17'"
         onmouseout="this.style.background='#e67e22'"
      >→ Projekt anfragen</a>
      
      
    </div>
  </div>
</div>
	





<h2 class="wp-block-heading">Handles vs. AddHandler</h2>



<p>In WinForms gibt es zwei Wege, ein Ereignis mit einer Methode zu verbinden:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">' Weg 1: Handles-Klausel (statisch, zur Designzeit)
Private Sub BtnSave_Click(sender As Object, e As EventArgs) Handles BtnSave.Click
    ' Wird automatisch vom Designer verdrahtet
End Sub

' Weg 2: AddHandler (dynamisch, zur Laufzeit)
AddHandler BtnSave.Click, AddressOf BtnSave_Click

Private Sub BtnSave_Click(sender As Object, e As EventArgs)
    ' Kein "Handles" nötig
End Sub</pre>



<p>Die <code>Handles</code>-Klausel funktioniert nur mit Controls, die zur Designzeit existieren. <code>AddHandler</code> funktioniert immer, auch mit Controls die du erst per Code erstellst. Sobald du Controls dynamisch erzeugst, ist <code>AddHandler</code> der einzige Weg.</p>



<h2 class="wp-block-heading">AddHandler Syntax</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">AddHandler Objekt.Ereignis, AddressOf MethodenName</pre>



<ul class="wp-block-list">
<li><code>Objekt.Ereignis</code> ist das Ereignis, das du abonnieren willst (z.B. <code>Button1.Click</code>)</li>



<li><code>AddressOf</code> gibt einen Verweis auf die Methode zurück, die aufgerufen werden soll</li>



<li>Die Signatur der Methode muss zum Ereignis passen (z.B. <code>sender As Object, e As EventArgs</code>)</li>
</ul>



<h2 class="wp-block-heading">Einfaches Beispiel</h2>



<p>Ein Button-Click per <code>AddHandler</code> statt <code>Handles</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        AddHandler BtnGreet.Click, AddressOf BtnGreet_Click
    End Sub

    Private Sub BtnGreet_Click(sender As Object, e As EventArgs)
        MessageBox.Show("Hallo!")
    End Sub
End Class</pre>



<p>Beachte, dass die Methode <code>BtnGreet_Click</code> kein <code>Handles</code> am Ende hat. Die Verknüpfung passiert ausschließlich über <code>AddHandler</code> im <code>Load</code>-Event.</p>



<h2 class="wp-block-heading">Dynamische Controls erstellen</h2>



<p>Der häufigste Einsatzfall für <code>AddHandler</code>: Controls werden per Code erzeugt und brauchen Event-Handler. Hier ein Beispiel mit dynamisch erstellten Buttons:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim categories = New List(Of String) From {
        "Privat", "Geschäft", "Archiv"
    }

    For Each category In categories
        Dim btn As New Button()
        btn.Text = category
        btn.Size = New Size(120, 40)
        btn.Margin = New Padding(5)
        AddHandler btn.Click, AddressOf CategoryButton_Click
        FlowLayoutPanel1.Controls.Add(btn)
    Next
End Sub

Private Sub CategoryButton_Click(sender As Object, e As EventArgs)
    Dim btn = DirectCast(sender, Button)
    MessageBox.Show($"Kategorie: {btn.Text}")
End Sub</pre>



<p>Jeder Button bekommt denselben Click-Handler. Über <code>DirectCast(sender, Button)</code> ermittelst du, welcher Button geklickt wurde. Das funktioniert mit beliebig vielen Controls, ohne dass du für jedes einen eigenen Handler brauchst.</p>



<h2 class="wp-block-heading">Komplettes Beispiel: Numpad-Tastatur</h2>



<p>Ein realistisches Beispiel, das eine virtuelle Numpad-Tastatur zur Laufzeit erstellt. Jeder Tasten-Button wird per <code>AddHandler</code> mit einem gemeinsamen Handler verbunden:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim keys = New List(Of String) From {
            "7", "8", "9",
            "4", "5", "6",
            "1", "2", "3",
            "0", "00", ","
        }

        For Each key In keys
            Dim btn As New Button()
            btn.Text = key
            btn.Size = New Size(50, 50)
            btn.FlatStyle = FlatStyle.Flat
            btn.FlatAppearance.BorderSize = 1
            btn.BackColor = Color.White
            btn.Font = New Font("Segoe UI", 12, FontStyle.Bold)
            AddHandler btn.Click, AddressOf NumpadButton_Click
            FlowLayoutPanel1.Controls.Add(btn)
        Next
    End Sub

    Private Sub NumpadButton_Click(sender As Object, e As EventArgs)
        Dim btn = DirectCast(sender, Button)
        TextBox1.Text &= btn.Text
    End Sub
End Class</pre>



<p>Du brauchst dafür nur ein <code>FlowLayoutPanel</code> (ca. 180 x 260 Pixel) und eine <code>TextBox</code> auf dem Form. Die Buttons werden komplett per Code erstellt, kein Designer nötig.</p>


<div style="box-sizing:border-box;margin:36px 0;border-radius:12px;overflow:hidden;background:#1a1a2e;position:relative;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
  <div style="position:absolute;inset:0;background-image:linear-gradient(rgba(255,255,255,0.03) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,0.03) 1px,transparent 1px);background-size:40px 40px;pointer-events:none;"></div>
  <div style="position:absolute;top:-60px;right:-60px;width:240px;height:240px;background:radial-gradient(circle,rgba(230,126,34,0.18) 0%,transparent 70%);pointer-events:none;"></div>
  <div style="position:relative;padding:32px 28px;">

        <div style="display:inline-block;font-size:11px;font-weight:700;letter-spacing:2.5px;text-transform:uppercase;color:#e67e22;margin-bottom:14px;border:1px solid rgba(230,126,34,0.35);border-radius:4px;padding:3px 10px;">Projekt in Planung?</div>
    
        <p style="margin:0 0 10px 0;font-size:clamp(17px,4vw,21px);font-weight:700;color:#ffffff;line-height:1.35;">Brauchst du eine fertige WinForms-Anwendung?</p>
    
        <p style="margin:0 0 24px 0;font-size:14px;color:rgba(255,255,255,0.65);line-height:1.7;max-width:540px;">Von Event-Handling bis zur kompletten datengetriebenen Desktop-App: Ich entwerfe Software, die hält. Lass uns über dein Projekt sprechen.</p>
    
    <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:center;">

            <a href="https://robbelroot.de/kontakt/"
         style="display:inline-block;padding:12px 24px;background:#e67e22;color:#ffffff;font-size:14px;font-weight:700;text-decoration:none;border-radius:7px;letter-spacing:0.3px;transition:background .2s ease;white-space:nowrap;"
         onmouseover="this.style.background='#cf6d17'"
         onmouseout="this.style.background='#e67e22'"
      >→ Projekt anfragen</a>
      
      
    </div>
  </div>
</div>
	


<h2 class="wp-block-heading">RemoveHandler: Ereignis wieder trennen</h2>



<p>Mit <code>RemoveHandler</code> trennst du die Verbindung wieder. Das ist wichtig, um Memory Leaks zu vermeiden, wenn Controls zur Laufzeit entfernt werden:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">' Handler zuweisen
AddHandler btn.Click, AddressOf Button_Click

' Handler wieder entfernen
RemoveHandler btn.Click, AddressOf Button_Click</pre>



<p>Verwende <code>RemoveHandler</code> immer dann, wenn:</p>



<ul class="wp-block-list">
<li>Du dynamische Controls <strong>entfernst</strong> (z.B. beim Schließen eines Tabs)</li>



<li>Du den Handler <strong>austauschen</strong> willst (erst Remove, dann Add)</li>



<li>Du verhindern willst, dass ein Event <strong>mehrfach</strong> feuert</li>
</ul>



<h2 class="wp-block-heading">Mehrere Events, ein Handler</h2>



<p>Ein Handler kann mehrere Events verarbeiten. Das ist besonders nützlich bei Formularen mit vielen ähnlichen Controls:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    AddHandler TxtName.TextChanged, AddressOf ValidateField
    AddHandler TxtEmail.TextChanged, AddressOf ValidateField
    AddHandler TxtPhone.TextChanged, AddressOf ValidateField
End Sub

Private Sub ValidateField(sender As Object, e As EventArgs)
    Dim txt = DirectCast(sender, TextBox)
    If String.IsNullOrWhiteSpace(txt.Text) Then
        txt.BackColor = Color.MistyRose
    Else
        txt.BackColor = Color.White
    End If
End Sub</pre>



<p>Alle drei TextBoxen teilen sich den <code>ValidateField</code>-Handler. Über <code>sender</code> wird erkannt, welche TextBox sich geändert hat.</p>



<h2 class="wp-block-heading">Eigene Events mit AddHandler</h2>



<p>Du kannst auch eigene Events definieren und per <code>AddHandler</code> abonnieren. Das ist nützlich für lose gekoppelte Kommunikation zwischen Klassen:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Public Class FileWatcher
    Public Event FileChanged(filePath As String)

    Public Sub CheckForChanges()
        ' Prüflogik...
        RaiseEvent FileChanged("C:\data\config.xml")
    End Sub
End Class

' Im Form:
Private WithEvents watcher As New FileWatcher()

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    AddHandler watcher.FileChanged, AddressOf OnFileChanged
End Sub

Private Sub OnFileChanged(filePath As String)
    MessageBox.Show($"Datei geändert: {filePath}")
End Sub</pre>



<p>Mit <code>RaiseEvent</code> löst die Klasse das Event aus. Der Abonnent reagiert darauf per <code>AddHandler</code>. So bleibt die <code>FileWatcher</code>-Klasse unabhängig vom Form.</p>



<h2 class="wp-block-heading">Häufige Fehler</h2>



<h3 class="wp-block-heading">Handler wird mehrfach registriert</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">' SCHLECHT - bei jedem Klick wird ein weiterer Handler hinzugefügt
Private Sub BtnRefresh_Click(sender As Object, e As EventArgs) Handles BtnRefresh.Click
    AddHandler Timer1.Tick, AddressOf Timer1_Tick
End Sub

' GUT - Handler nur einmal im Load registrieren
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    AddHandler Timer1.Tick, AddressOf Timer1_Tick
End Sub</pre>



<p>Wenn du <code>AddHandler</code> mehrfach für dasselbe Event und dieselbe Methode aufrufst, wird die Methode auch mehrfach ausgeführt. Registriere Handler in <code>Load</code> oder stelle sicher, dass du vorher <code>RemoveHandler</code> aufrufst. Zum Thema Timer gibt es auch den <a href="https://robbelroot.de/blog/vbnet-timer/"><strong>VB.NET Timer Guide</strong></a>.</p>



<h3 class="wp-block-heading">Falsche Methodensignatur</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">' SCHLECHT - Parameter stimmen nicht mit dem Event überein
Private Sub Button_Click(text As String)
End Sub

' GUT - Signatur passt zum Click-Event
Private Sub Button_Click(sender As Object, e As EventArgs)
End Sub</pre>



<p>Die Methode muss exakt die Parameter-Typen haben, die das Event erwartet. Bei <code>Click</code> ist das <code>(sender As Object, e As EventArgs)</code>. Der Compiler meldet einen Fehler, wenn die Signatur nicht passt.</p>



<h3 class="wp-block-heading">RemoveHandler vergessen bei dynamischen Controls</h3>



<p>Wenn du Controls per <code>Controls.Remove()</code> entfernst, aber den Handler nicht trennst, hält die Referenz das Objekt im Speicher. Rufe immer <code>RemoveHandler</code> auf, bevor du ein dynamisches Control entfernst.</p>


<div style="box-sizing:border-box;margin:36px 0;border-radius:12px;overflow:hidden;background:#1a1a2e;position:relative;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
  <div style="position:absolute;inset:0;background-image:linear-gradient(rgba(255,255,255,0.03) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,0.03) 1px,transparent 1px);background-size:40px 40px;pointer-events:none;"></div>
  <div style="position:absolute;top:-60px;right:-60px;width:240px;height:240px;background:radial-gradient(circle,rgba(230,126,34,0.18) 0%,transparent 70%);pointer-events:none;"></div>
  <div style="position:relative;padding:32px 28px;">

        <div style="display:inline-block;font-size:11px;font-weight:700;letter-spacing:2.5px;text-transform:uppercase;color:#e67e22;margin-bottom:14px;border:1px solid rgba(230,126,34,0.35);border-radius:4px;padding:3px 10px;">Interessiert?</div>
    
        <p style="margin:0 0 10px 0;font-size:clamp(17px,4vw,21px);font-weight:700;color:#ffffff;line-height:1.35;">Erfahrenen .NET-Entwickler gesucht?</p>
    
        <p style="margin:0 0 24px 0;font-size:14px;color:rgba(255,255,255,0.65);line-height:1.7;max-width:540px;">Ich übernehme dein Projekt, von Event-Handling bis zur fertigen Desktop-Anwendung. Schreib mir einfach eine Nachricht.</p>
    
    <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:center;">

            <a href="https://robbelroot.de/kontakt/"
         style="display:inline-block;padding:12px 24px;background:#e67e22;color:#ffffff;font-size:14px;font-weight:700;text-decoration:none;border-radius:7px;letter-spacing:0.3px;transition:background .2s ease;white-space:nowrap;"
         onmouseover="this.style.background='#cf6d17'"
         onmouseout="this.style.background='#e67e22'"
      >→ Projekt anfragen</a>
      
      
    </div>
  </div>
</div>
	


<h2 class="wp-block-heading">FAQ</h2>



<div class="schema-faq wp-block-yoast-faq-block"><div class="schema-faq-section" id="faq-addhandler-de-1"><strong class="schema-faq-question"><strong>Was ist der Unterschied zwischen Handles und AddHandler?</strong></strong> <p class="schema-faq-answer"><code>Handles</code> verknüpft ein Event statisch zur Designzeit mit einer Methode. <code>AddHandler</code> verknüpft ein Event dynamisch zur Laufzeit. Für Controls die per Code erstellt werden, ist <code>AddHandler</code> der einzige Weg.</p> </div> <div class="schema-faq-section" id="faq-addhandler-de-2"><strong class="schema-faq-question"><strong>Kann ich AddHandler mehrfach für dasselbe Event aufrufen?</strong></strong> <p class="schema-faq-answer">Ja, aber dann wird der Handler auch mehrfach ausgeführt. Falls du das nicht willst, rufe vorher <code>RemoveHandler</code> auf oder registriere den Handler nur einmal im <code>Load</code>-Event.</p> </div> <div class="schema-faq-section" id="faq-addhandler-de-3"><strong class="schema-faq-question"><strong>Wann brauche ich RemoveHandler?</strong></strong> <p class="schema-faq-answer">Immer wenn du dynamische Controls entfernst, Handler austauschen willst oder verhindern möchtest, dass ein Event mehrfach feuert. Ohne <code>RemoveHandler</code> kann es zu Memory Leaks kommen.</p> </div> <div class="schema-faq-section" id="faq-addhandler-de-4"><strong class="schema-faq-question"><strong>Kann ein Handler mehrere Events verarbeiten?</strong></strong> <p class="schema-faq-answer">Ja. Verwende <code>AddHandler</code> mehrfach mit verschiedenen Controls, aber derselben Methode. Über den <code>sender</code>-Parameter erkennst du, welches Control das Event ausgelöst hat.</p> </div> <div class="schema-faq-section" id="faq-addhandler-de-5"><strong class="schema-faq-question"><strong>Was bedeutet AddressOf in VB.NET?</strong></strong> <p class="schema-faq-answer"><code>AddressOf</code> erstellt einen Delegate, also einen typisierten Verweis auf eine Methode. Er wird zusammen mit <code>AddHandler</code> verwendet, um dem Event mitzuteilen, welche Methode aufgerufen werden soll.</p> </div> </div>



<h2 class="wp-block-heading">Fazit</h2>



<p>Die <code>AddHandler</code>-Anweisung macht dein Event-Handling in VB.NET flexibel. Verwende sie für dynamisch erstellte Controls, wenn du Handler zur Laufzeit zuweisen oder austauschen willst, und für eigene Events in deinen Klassen. Denke daran, <code>RemoveHandler</code> aufzurufen, wenn du Controls entfernst, und registriere Handler nur einmal, um Mehrfach-Ausführungen zu vermeiden. Für verwandte Themen schau dir den <a href="https://robbelroot.de/blog/vbnet-timer/"><strong>VB.NET Timer Guide</strong></a> und den <a href="https://robbelroot.de/blog/vbnet-list/"><strong>VB.NET List Guide</strong></a> an.</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vbnet-addhandler/">VB.NET AddHandler – Events dynamisch verknüpfen (2026)</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/vbnet-addhandler/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
