How to add buttons to 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 do not want to create a form at runtime, but add dynamically created buttons to the current Winform ie: GUIWevDav

thank

+3
source share
3 answers

The problem in your code is that you are trying to call a method Controls.Add()on GUIWevbDav, which is a type of your form, and you cannot get Control.Add for a type, it is not a static method. It only works with 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 not a static method. It only works on instances.
    //GUIWevbDav.Controls.Add

}
+6
source

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

+7
source

Control.Controls. Form Class Members Controls.

:

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

Source: https://habr.com/ru/post/1752766/


All Articles