<?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>dynamically Archive - Robert Skibbe</title>
	<atom:link href="https://robbelroot.de/blog/tag/dynamically/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>alias RobbelRoot – Freelance Full Stack Developer .NET</description>
	<lastBuildDate>Sat, 04 Nov 2023 12:33:59 +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>dynamically 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>
	</channel>
</rss>
