添加控件步骤

(1)实例化一个控件;

(2)设置控件实例属性;

(3)将控件实例添加到窗体的Controls集合中

【示例】

(1)在Visual Studio中新建一个“Windos 窗体应用程序”

(2)窗体代码Form1.cs如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

//实例化一个命令按钮
Button btn = new Button();

//设置命令按钮的属性
btn.Location = new Point(50, 50);
btn.Size = new Size(80, 25);
btn.Text = "退出";
btn.Click += btn_Click;

//添加到窗口的Controls集合中
this.Controls.Add(btn);
}
void btn_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

(3)运行效果
窗体启动后:


相关链接(侵删)

  1. C#如何用代码向窗体中添加控件?)

=================我是分割线=================

欢迎到公众号来唠嗑: