ASP.NET – C# – Emulating the VB Control Array – Pt. 1

For you veterans of VB6, the control array probably became an old friend, or at least an annoying neighbor if you didn’t like them.  You couldn’t help run across the concept in VB6 because every time you copy and pasted a control for the first time, you got asked if you wanted to create a control array.

If you say yes, VB creates an array for you with the same name and type as the control you copied and begins assigning values to the index property of the original and all new copies.  Keep pasting and the array just grows.  You reference individual instances of the control like:  myControl[0].Text for first instnace, myControl[1].text for second instance, and so on.

But now you’ve made the switch to C#, or if you just couldn’t let it go, hopefully to VB.Net, and you’re wondering what the heck happened to the control arrays.  Well, the short answer is, they’re gone!  The control array of yore was great if you needed a bunch of textboxes, radio buttons, or checkboxes that you would run through a For Each or For Next loop.  That need hasn’t magically gone away, so what’s a developer to do?

This article will discuss how to emulate a control array or an array of html form elements in ASP.Net using C# code.  Translating to VB.Net should be relatively painless once you catch the drift.

Server Controls vs. HTML Form Elements

First, it bears remembering that in ASP.NET, you get to choose between Server Controls like the TextBox (aka System.Web.UI.WebControls.TextBox) and straight up HTML tags like <INPUT type=”text” name=”element_name” value=”” />.  Both of these can be used like a control array, but the methods are little different.

Lets look at the Server Control first…

Emulating Control Arrays with Server Controls

Before I jump into an example, here’s a rundown of the basic steps for emulating a Control Array with Server Controls:

  1. Create your controls that you want to target…give them IDs that start with a similar prefix
  2. Add your controls to a PlaceHolder control or some other object that has a controls collection.  This allows you to utilize the Controls Collection for easy looping
  3. Set up your function ForEach loop utilizing said Controls Collection of the parent

Jumping Right In

The first thing you need to do is get your controls created on your Web Form.  You can manually create your controls at design time, dragging and dropping from the Visual Studio toolbox into your form.  Or, you can create the controls at runtime.

The design time creation is blindingly straight forward, so we won’t go into that, and will do a quick example of runtime creation instead.  In this example, we’ll create 12 textboxes (1 for each month):

Start with a PlaceHolder

You need some means of placing your controls with some level of precision in your form.  ASP.Net provides the PlaceHolder control to which you can .Add controls.  So drag a PlaceHolder from the toolbox to the place in your document where you want your textboxes to go.  It gets a name like PlaceHolder1.

Function for Creating/Adding Controls

If you’re creating a whole bunch of similar controls, hopefully you’ve got a list, a datatable, or an array to loop through, else your code will be slightly more lengthy.  Here’s a simple For loop that will create the 12 textboxes for the months.  Note that it uses a little string formatting to pop the month name in the newly created textboxes.  SteveX has a super helpful reference and FAQ for string formatting.  Thanks, Steve!
protected void addMonthTextBoxes()
//Set up the for loop
for (int i = 1; i < 13; i++) { TextBox tt = new TextBox(); // Note that we are prefixing our ID with something that is smiliar tt.ID = "month" + i; tt.Text = string.Format("{0:MMMM}", DateTime.Parse( i + "/1/2008")); PlaceHolder1.Controls.Add(tt); } }[/sourcecode] Call your function from the Page_Load function, and upon execution, you should have 12 textboxes with the Month names in them.

Setting up a Button and a Handler Function

Now that you’ve got your textboxes going, drag a button onto your Web Form and double click it to get to the codebehind function that will handle it.  Inside the button’s click function, use the following code to loop through the Controls Collection of the PlaceHolder you created.  Note that most, if not all, server controls will have a Controls Collection that you can access and do a ForEach loop on.  Here’s the code:

protected void btnRefresh_Click(object sender, EventArgs e)
foreach (Control c in PlaceHolder1.Controls){
//In this case, we’re only looking for TextBox controls…use GetType() to test it
if (c.GetType().ToString().Equals(“System.Web.UI.WebControls.TextBox”)){// We look at the Control’s ID to see if it starts with the our unique prefix
if (c.ID.StartsWith(“month”)){

Note that we don’t have an index or even the good old Tag
VB6.  One way to emulate those properties is to use the “suffix” of your ID.
In this case, we used the Month #.  So, parsing the ID string by stripping
off ‘month’ would leave us with the month #.  And we can use as needed.
*/ property from

//We have to cast the control as a textbox to use it
TextBox tb = (TextBox)c;
//Do something with ‘tb’, the text box we found.. e.g.  tb.Text = “Hello ” + tb.Text

Notice that the key is being able to loop through the PlaceHolder’s Controls Collection.  You could loop through the Controls Collection of any control on your form.  Even the Form itself like so:

foreach ( Control c in Form.Controls){ …. }

This foreach only gets the immediate child controls of the Form object.  If you do not know the particular parent or parents of your target controls, you will need to use a recursive function that walks through the Children of each control on the form.  Not the most efficient means of processing, but it works.

See Part 2 for Using HTML Form Elements like Control Arrays

That’s it for emulating control arrays with ASP.Net Server Controls.  I’m sure there’s much more that could be written, but that’s all I’ve got in me today.  Demonstrating the recursive function that walks all the children of the Form object would be a good start…maybe later.

Part 2 of this post will show how to use a straight up html form element, ie INPUT tags that don’t runat server, as arrays.  For those of you with PHP background, you know how nice PHP is to place those for you in an Array through $_REQUEST, $_GET, and $_POST.  We’ll see how we can do that in ASP.Net.  Hopefully I’ll get that done in the near, near future.




5 Responses to ASP.NET – C# – Emulating the VB Control Array – Pt. 1

  1. Ormond April 21, 2009 at 2:50 am #

    Thank you, just what I’ve been looking for! Can you point me to a location for the VB syntax?

  2. Byron Bennett April 21, 2009 at 7:28 am #

    Hi Ormond,

    Sorry, but it’s been a long time since I’ve done any VB, back to the old VB6 days in fact. Too much has changed for me to attempt to translate. VB and C# are quite similar these days, I just don’t know where they are similar and where they differ any more.

    You might be able to work through it. If you try and get stuck on any part, let me know and I’ll try to help.


  3. Ormond April 21, 2009 at 4:06 pm #

    Thanks, I’ve found which is quite fun. I’ve managed to figure out the creation of (in my case) a collection of hyperlinks but I’m having trouble controlling the collection – I want to delete the entire collection before opening a text file and recreating it from new. The C# code for the handler you have given won’t translate, any ideas?

  4. Jeff March 30, 2010 at 4:13 am #

    I am using your example to create the control array however I am not sure how to go about formatting the controls on the webpage since it is done at runtime.

  5. Byron Bennett March 30, 2010 at 7:23 am #

    Hi Jeff,

    In the function: addMonthTextBoxes()

    add something like: tt.CSSClass = ‘my_class’;

    Then you can style it in your CSS style sheet.


Powered by WordPress. Designed by Woo Themes