简体   繁体   中英

C# .Net 4.5 How do I create a button on form load in code view?

I am attempting to create/instantiate a button on a standard windows form (on load) by using the code view exclusively. I'm trying to do something like this:

Barebones Example: NOTE: Don't sweat the format here. I'm just summarizing.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

SomeClass BlahFooBarBaz
{
    private void Form1_Load(object sender, EventArgs e)
    {
        Button newBtn = new Button();
        newBtn.Width = 25;
        newBtn.Height = 25;
        newBtn.Visible = true;
        Point p = new Point(Location.X, y);
        newBtn.Text = "Test";
    }
}

When I execute this, I get a blank form. Will this code work if I set the correct properties, or is there something else I need to do?

您需要将按钮添加到表单中:

this.Controls.Add(newBtn);

You have to add your button to your form, or another container (for example a Panel).

Currently your button is just a local variable, destroyed at the end of "Load" method.

It's the same for your "p" Point : I guess you would like to use it to set the position of your button, but currently you don't tie one to other. And you pass to "p" constructor inexistant variables.

Here is a working form load (with arbitrary values for p) :

    private void Form1_Load(object sender, EventArgs e)
    {
        Button newBtn = new Button();
        newBtn.Width = 25;
        newBtn.Height = 25;
        newBtn.Visible = true;
        Point p = new Point(100, 100);
        newBtn.Text = "Test";
        newBtn.Location = p;

        this.Controls.Add(newBtn);
    }

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