简体   繁体   中英

Windows Forms - Create a button in a form from another form

So I am having this problem: I want to create a button when I click a different button in a 2nd form. I have a button in my 2nd from with this code:

Button test = new Button();
test.Text = "New Button";
test.Location = new Point(0, 0);
panel4.Controls.Add(test);

It successfully add the button to panel4. Now I want to do this but in a different panel that is in my form1. Ultimately I would like to add that button to a table cell.

You can use form1.differentPanel.Add(test); (and you'll have to add uses form1 in form2)

I suspect that the reason your question was down-voted is because this is not the professional way to use forms. In large professional projects the idea is to have as little code as possible in forms and to keep forms and business logic separated. It's Ok to start off this way when you are just learning the language. Although purists will probably say that it's not Ok and you should use best practices from the start.

Consider Your are On Form1

Make panel4 Public on Form2

        Form2 o = new Form2();
        Button test = new Button();
        test.Text = "New Button";
        test.Location = new Point(0, 0);
        o.panel4.Controls.Add(test);
        o.Show();

https://youtu.be/WWPwBI4NdlU

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM