Simsons
Simsons

Reputation: 12735

How to add Buttons in WinForm in Runtime?

I have the following Code :

public GUIWevbDav()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    try
    {
        //My XML Loading and other Code Here

        //Trying to add Buttons here
        if (DisplayNameNodes.Count > 0)
        {
            for (int i = 0; i < DisplayNameNodes.Count; i++)
            {
                Button folderButton = new Button();
                folderButton.Width = 150;
                folderButton.Height = 70;
                folderButton.ForeColor = Color.Black;
                folderButton.Text = DisplayNameNodes[i].InnerText;

                Now trying to do  GUIWevbDav.Controls.Add
                (unable to get GUIWevbDav.Controls method )

            }
        }

I dont want to create a form at run time but add the dynamically created buttons to my Current Winform i.e: GUIWevDav

Thanks

Upvotes: 3

Views: 12253

Answers (3)

this. __curious_geek
this. __curious_geek

Reputation: 43207

Problem in your code is that you're trying to call Controls.Add() method on GUIWevbDav which is the type of your form and you can't get Control.Add on a type, it's not a static method. It only works on instances.

for (int i = 0; i < DisplayNameNodes.Count; i++) 
{ 

    Button folderButton = new Button(); 
    folderButton.Width = 150; 
    folderButton.Height = 70; 
    folderButton.ForeColor = Color.Black; 
    folderButton.Text = DisplayNameNodes[i].InnerText; 

    //This will work and add button to your Form.
    this.Controls.Add(folderButton );

    //you can't get Control.Add on a type, it's not a static method. It only works on instances.
    //GUIWevbDav.Controls.Add

}

Upvotes: 6

Incognito
Incognito

Reputation: 16577

You need to work with Control.Controls property. In Form Class Members you can see Controls property.

Use it like this :

this.Controls.Add(folderButton);  // "this" is your form class object. 

Upvotes: 3

Petar Minchev
Petar Minchev

Reputation: 47363

Just use this.Controls.Add(folderButton). this is your form.

Upvotes: 8

Related Questions