Skip to content

WinForm 常用控件及使用方法

WinForm 是 .NET Framework 提供的 Windows 桌面应用程序开发框架,包含丰富的控件库。以下是 WinForm 中常用控件的分类介绍和使用方法。

一、基础控件

1. Button(按钮)

用途:触发操作

csharp
// 添加点击事件
button1.Click += (sender, e) => {
    MessageBox.Show("按钮被点击");
};

// 设置属性
button1.Text = "点击我";
button1.BackColor = Color.LightBlue;
button1.Enabled = true; // 启用/禁用按钮

2. Label(标签)

用途:显示文本

csharp
label1.Text = "用户名:";
label1.ForeColor = Color.Red;
label1.Font = new Font("微软雅黑", 12);

3. TextBox(文本框)

用途:输入文本

csharp
// 获取输入内容
string input = textBox1.Text;

// 设置属性
textBox1.PasswordChar = '*'; // 密码框
textBox1.Multiline = true;   // 多行文本框
textBox1.ScrollBars = ScrollBars.Vertical; // 滚动条

4. CheckBox(复选框)

用途:多项选择

csharp
if (checkBox1.Checked)
{
    // 被选中时的逻辑
}

// 三态复选框
checkBox1.ThreeState = true;

5. RadioButton(单选按钮)

用途:单项选择

csharp
if (radioButton1.Checked)
{
    // 选中选项1
}
else if (radioButton2.Checked)
{
    // 选中选项2
}

二、容器控件

1. Panel(面板)

用途:分组控件

csharp
panel1.BorderStyle = BorderStyle.FixedSingle;
panel1.AutoScroll = true; // 自动滚动

2. GroupBox(分组框)

用途:带标题的分组

csharp
groupBox1.Text = "用户信息";

3. TabControl(选项卡)

用途:多页面切换

csharp
// 添加选项卡页
TabPage page1 = new TabPage("基本信息");
tabControl1.TabPages.Add(page1);

// 切换事件
tabControl1.SelectedIndexChanged += (s, e) => {
    MessageBox.Show($"切换到第{tabControl1.SelectedIndex}页");
};

三、列表控件

1. ListBox(列表框)

用途:显示项目列表

csharp
// 添加项目
listBox1.Items.Add("项目1");
listBox1.Items.AddRange(new[] { "项目2", "项目3" });

// 多选设置
listBox1.SelectionMode = SelectionMode.MultiExtended;

// 获取选中项
foreach (var item in listBox1.SelectedItems)
{
    Console.WriteLine(item.ToString());
}

2. ComboBox(组合框)

用途:下拉选择

csharp
comboBox1.Items.AddRange(new[] { "选项1", "选项2", "选项3" });
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; // 禁止编辑

// 选中事件
comboBox1.SelectedIndexChanged += (s, e) => {
    MessageBox.Show($"选择了:{comboBox1.SelectedItem}");
};

3. ListView(列表视图)

用途:高级列表显示

csharp
// 设置视图模式
listView1.View = View.Details;

// 添加列
listView1.Columns.Add("ID", 50);
listView1.Columns.Add("名称", 100);

// 添加项
ListViewItem item = new ListViewItem("1");
item.SubItems.Add("张三");
listView1.Items.Add(item);

四、高级控件

1. DataGridView(数据网格)

用途:表格数据显示

csharp
// 绑定数据
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add("1", "张三");
dt.Rows.Add("2", "李四");

dataGridView1.DataSource = dt;

// 设置列属性
dataGridView1.Columns["Name"].HeaderText = "姓名";
dataGridView1.Columns["ID"].Width = 50;

// 单元格点击事件
dataGridView1.CellClick += (s, e) => {
    var value = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
};

2. TreeView(树形视图)

用途:层次结构显示

csharp
// 添加节点
TreeNode root = new TreeNode("根节点");
root.Nodes.Add("子节点1");
root.Nodes.Add("子节点2");
treeView1.Nodes.Add(root);

// 节点选择事件
treeView1.AfterSelect += (s, e) => {
    MessageBox.Show($"选择了:{e.Node.Text}");
};

3. DateTimePicker(日期选择)

用途:日期时间选择

csharp
// 获取选择的值
DateTime selectedDate = dateTimePicker1.Value;

// 设置格式
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "yyyy年MM月dd日";

五、菜单和工具栏

1. MenuStrip(菜单栏)

csharp
// 创建菜单
MenuStrip menu = new MenuStrip();
ToolStripMenuItem fileMenu = new ToolStripMenuItem("文件(&F)");
fileMenu.DropDownItems.Add("新建", null, (s, e) => NewFile());
fileMenu.DropDownItems.Add("退出", null, (s, e) => Close());

menu.Items.Add(fileMenu);
this.Controls.Add(menu);

2. ToolStrip(工具栏)

csharp
ToolStrip toolStrip = new ToolStrip();
toolStrip.Items.Add(new ToolStripButton("保存", null, (s, e) => Save()));
toolStrip.Items.Add(new ToolStripSeparator());
toolStrip.Items.Add(new ToolStripButton("打印", null, (s, e) => Print()));

this.Controls.Add(toolStrip);

六、对话框控件

1. OpenFileDialog(打开文件)

csharp
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "文本文件|*.txt|所有文件|*.*";
if (openFile.ShowDialog() == DialogResult.OK)
{
    string filePath = openFile.FileName;
    // 处理文件
}

2. SaveFileDialog(保存文件)

csharp
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.Filter = "文本文件|*.txt";
if (saveFile.ShowDialog() == DialogResult.OK)
{
    File.WriteAllText(saveFile.FileName, "文件内容");
}

3. FolderBrowserDialog(选择文件夹)

csharp
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
if (folderDialog.ShowDialog() == DialogResult.OK)
{
    string folderPath = folderDialog.SelectedPath;
}

七、布局技巧

1. Anchor(锚定)

csharp
// 控件随窗体大小调整
button1.Anchor = AnchorStyles.Top | AnchorStyles.Right;

2. Dock(停靠)

csharp
// 控件填充整个区域
dataGridView1.Dock = DockStyle.Fill;

3. TableLayoutPanel(表格布局)

csharp
tableLayoutPanel1.ColumnCount = 2;
tableLayoutPanel1.RowCount = 2;
tableLayoutPanel1.Controls.Add(button1, 0, 0);
tableLayoutPanel1.Controls.Add(button2, 1, 0);

八、数据绑定

1. 简单数据绑定

csharp
textBox1.DataBindings.Add("Text", customer, "Name");

2. 复杂数据绑定

csharp
listBox1.DataSource = customerList;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "ID";

最佳实践

  1. 命名规范:使用有意义的控件名称(如btnSave、txtUserName)
  2. 事件处理:避免在窗体中堆积过多事件处理逻辑,使用单独的方法
  3. 线程安全:跨线程更新UI使用Control.Invoke
  4. 资源释放:实现IDisposable接口释放非托管资源
  5. 用户反馈:长时间操作时使用BackgroundWorker或异步方法

✨ 网站运行时间: 3年11月15天 ❤️ 道阻且长,行则将至 - 微信号: heikedreamer