Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

C# - Dynamic Controls

form

  • Please log in to reply
4 replies to this topic

#1 CommittedC0der

CommittedC0der

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1065 posts
  • Programming Language:C#
  • Learning:C#, JavaScript, PL/SQL

Posted 12 August 2011 - 01:52 PM

Hello everyone! Today we'll be going over the topic of dynamically created controls, otherwise known as controls created at runtime(while the program is running). I assume you know a control is any object from the tool box, but if you didn't, you do now. :)

I'd like to mention that knowledge in the following areas will help.
  • ArrayLists.
  • Functions.
  • Control properties.
  • Event Handlers
Dynamic Control Uses.
Before we get started we should at least know when and why we use dynamic controls.

When.
A basic example is to say you’re making a contacts application, and you have an add contacts button. Now when you press this button a new category is added, which is full of controls to edit the details of the new contact. In this case the application cannot have a limit to the number of contact it contains, so it needs to dynamically create new controls for every new contact.

Why.
With the above example, you could just add the controls to the form during design time, out of site, or hide() them. But after about 5 or so new contacts your going have a huge, huge mess on your hands. With dynamically created controls you can save a lot of time, and have much cleaner and more efficient code.


Creating Controls.
Before we create our controls we'll need a new project, and a button on the form. For this tutorial we'll be creating our controls in functions, you don't have to use a function but I like to because the code is re-usable and keeps the event area much cleaner. With that settled double click the button to enter our code view and create a new function and call it on our button click.
public void createButton()
{
 
}
 
private void button1_Click(object sender, EventArgs e)
{
 createButton();
}

If you couldn't tell, our dynamic control will be buttons for this tutorial.

Now let’s add this code to our function.
Button btn = new Button();
btn.Text = "CodeCall Rules!";
btn.Location = new Point(50, 50);

Let’s review. First we create a new instance of ANY control we want, in this case a button named "btn". We then assign our new "btn"s text to "CodeCall Rules!" and set its location to (50,50). Easy enough! Now we need to add this new control to the form.
this.Controls.Add(btn);

This should be self explanatory, all we do is add the new control we just created, "btn", to "this"(the Form).

Congratulations! You've just created your first dynamic control! In the next step we'll add some more features.

More Dynamic!
First off there are a couple things wrong with our current button. 1st, Its text is always "CodeCall Rules" and 2nd, Its locations is stuck at (50,50). Now if you understand Functions you probably know what where doing next, adding some parameters.

Lets add three parameters, "x", "y", and "text" then we can incorporate them into our code.
public void createButton(int x, int y, string text)
{
Button btn = new Button();
btn.Text = text;
btn.Location = new Point(x, y);
this.Controls.Add(btn);
}
 
private void button1_Click(object sender, EventArgs e)
{
 createButton(100, 25, "Hello CodeCall");
}

There we have it, a pretty well working dynamic control! That really is the basics of dynamic controls. All controls can be made dynamically as longs as you change the instance and properties accordingly.

Even though that is jist of the tutorial, I do suggest you read the last part of this as it can come in very handy.


Event Handlers & Keeping Track of your Controls.
Well all that’s dandy and all, but what if you create three or four controls and need to know which one is being used? You’re going to have some issue's because once our function is done our control instance is as good as gone.

Tracking.
To keep track of our controls we must create a new arrayList and add them as there created. To do this we must first add.
using System.Collections;

Then create a new arrayList.
ArrayList btnList = new ArrayList();
Make sure you declare this outside of our function so we can reference it.

Now to add our buttons to the list in our function.
public void createButton(int x, int y, string text)
        {
            Button btn = new Button();
            btn.Text = text;
            btn.Location = new Point(x, y);            
            btnList.Add(btn);
 
            this.Controls.Add(btn);
        }

Now all of our "btn"s are saved in the arrayList so we can access them anytime we want.

Events.
For the last bit of this tutorial were going to learn how to add an event to our control(s). We'll also learn how to tell which one of our dynamic controls is being used in our event.

The first thing we must add is a new event handler to our button function.
btn.Click += new EventHandler(btn_Click);      

Now that we hace addad a Click eventHandler named "Btn_Click" to our "btn" lets add the actual eventHandler(This does NOT go in our function).
void btn_Click(object sender, EventArgs e)
{
}

With that done all that’s left to do is add the code to our eventHandler so we may see which button in our arrayList is being clicked.
Button btn = (Button)sender;
 MessageBox.Show("Dynamic Button " + btnList.IndexOf(btn) + " Clicked.");

Once again let’s review this code.
"Button btn (Button)sender;" creates a new instance of "btn" from the sender object, which is the butting being clicked.
"btnList.IndexOf(btn)" Now we call IndexOf() to find the index of our object, "btn", in our arrayList "btnList".

Try running your program and seeing if your dynamic control works. That's really it, I hope you understand clearly how to create and use dynamic controls to your advantage, any comments, suggestions, or rep welcome. :)
dynamic-button.png

Thanks ~ Committed.

Edited by CommittedC0der, 16 August 2011 - 10:58 AM.
Unefficient code.

  • 0
There IS a war going on for your mind.
Nothing of eternal significance happens besides prayer.

#2 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 16 August 2011 - 10:24 AM

Another great tutorial. What happens when btnCount = 20? Does the application crash? Is there a way to dynamically resize the array, or is there an alternate data structure like a list that you could use?
  • 0

#3 CommittedC0der

CommittedC0der

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1065 posts
  • Programming Language:C#
  • Learning:C#, JavaScript, PL/SQL

Posted 16 August 2011 - 10:39 AM

Well this one would crash, yes, but you could add a try-catch for that. I've been wanting to add an ArrayList in place of the array(They can be re-sized) but haven't had time, Ill get to it shortly.

EDIT: Fixed! :)

~Committed.
  • 0
There IS a war going on for your mind.
Nothing of eternal significance happens besides prayer.

#4 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 16 August 2011 - 11:14 AM

Awesome!
  • 0

#5 wadwmarmal

wadwmarmal

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 22 April 2013 - 02:29 AM

Another great tutorial. What happens when btnCount = 20? Does the application crash? Is there a way to dynamically resize the array, or is there an alternate data structure like a list that you could use?

 

check here a simple program to make a dynamic control with 4 lines.

 

http://csharp.net-in...controls-cs.htm

 

wade


  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download