DataGridView(数据表格)控件详解
本文面向零基础小白,所有代码都带详细注释。DataGridView 是 WinForms 里最重要、最强大的数据展示控件,务必重点掌握。
一、DataGridView 是什么
DataGridView(数据表格)用来以表格形式显示和编辑数据,类似 Excel。它支持数据绑定、排序、编辑、自定义样式等,是 WinForms 里最核心的数据控件。
基本信息
| 项目 | 内容 |
|---|---|
| 命名空间 | System.Windows.Forms |
| 继承关系 |
DataGridView → Control
|
| 在工具箱里的名字 | DataGridView |
| 核心作用 | 表格展示、编辑数据 |
最简单示例(绑定数据)
// 准备数据
List<Student> students = new List<Student>
{
new Student { Id = 1, Name = "张三", Age = 25 },
new Student { Id = 2, Name = "李四", Age = 22 },
};
// 直接绑定,表格自动生成列
dataGridView1.DataSource = students;
二、如何创建 DataGridView
方式 1:设计器拖拽
- 从工具箱拖入
DataGridView。 - 点右上角的小三角,选择数据源。
方式 2:代码创建
DataGridView dgv = new DataGridView();
dgv.Location = new Point(20, 20);
dgv.Size = new Size(500, 300);
this.Controls.Add(dgv);
三、DataGridView 的属性详解
3.1 数据类属性
DataSource —— 数据源(最重要)
// 绑定 List<T>(对象列表)
dataGridView1.DataSource = studentList;
// 绑定 DataTable
dataGridView1.DataSource = dataTable;
AutoGenerateColumns —— 自动生成列
dataGridView1.AutoGenerateColumns = true; // 根据数据自动生成列(默认)
dataGridView1.AutoGenerateColumns = false; // 手动定义列
3.2 选择相关
SelectionMode —— 选择模式
| 值 | 说明 |
|---|---|
FullRowSelect |
整行选中(推荐) |
CellSelect |
选中单个单元格(默认) |
RowHeaderSelect |
点行头选中整行 |
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 整行选中
MultiSelect —— 多选
dataGridView1.MultiSelect = true; // 允许多选(默认)
dataGridView1.MultiSelect = false; // 只能选一行
CurrentRow —— 当前行
DataGridViewRow row = dataGridView1.CurrentRow; // 当前行
3.3 行为类属性
ReadOnly —— 只读
dataGridView1.ReadOnly = true; // 用户不能编辑
AllowUserToAddRows —— 允许添加行
dataGridView1.AllowUserToAddRows = false; // 隐藏底部"新增"空行(推荐)
AllowUserToDeleteRows —— 允许删除行
dataGridView1.AllowUserToDeleteRows = false; // 不允许删除
3.4 外观类属性
AutoSizeColumnsMode —— 列宽模式
| 值 | 说明 |
|---|---|
Fill |
列自动填满整个表格(推荐) |
AllCells |
按内容宽度 |
DisplayedCells |
按显示内容宽度 |
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; // 填满
RowHeadersVisible —— 行头显示
dataGridView1.RowHeadersVisible = false; // 隐藏行头
AlternatingRowsDefaultCellStyle —— 隔行变色
// 隔行变色(斑马纹)
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
ColumnHeadersHeight —— 列头高度
dataGridView1.ColumnHeadersHeight = 35; // 列头高度
四、DataGridView 的事件详解
4.1 CellClick —— 点击单元格
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
// e.RowIndex 是行索引,e.ColumnIndex 是列索引
MessageBox.Show($"点击了第 {e.RowIndex} 行,第 {e.ColumnIndex} 列");
}
4.2 SelectionChanged —— 选中改变
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
// 判断是否有当前行
if (dataGridView1.CurrentRow != null)
{
// 读取当前行某列的值
var name = dataGridView1.CurrentRow.Cells["Name"].Value;
lblTip.Text = "选中:" + name;
}
}
4.3 CellFormatting —— 单元格渲染(改样式)
什么时候触发:单元格要显示时触发,可以动态改颜色。
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// 判断是否是"分数"列
if (dataGridView1.Columns[e.ColumnIndex].Name == "Score")
{
// 如果分数小于 60,显示红色
if (e.Value != null && Convert.ToDecimal(e.Value) < 60)
{
e.CellStyle.ForeColor = Color.Red;
}
}
}
4.4 CellDoubleClick —— 双击单元格
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
MessageBox.Show("双击了第 " + e.RowIndex + " 行");
}
}
五、DataGridView 的方法
| 方法 | 说明 |
|---|---|
dataGridView1.Rows.Add(...) |
添加行 |
dataGridView1.Rows.Remove(row) |
删除行 |
dataGridView1.Rows.Clear() |
清空 |
dataGridView1.Refresh() |
刷新 |
// 手动添加一行(不用数据绑定)
dataGridView1.Rows.Add(1, "张三", 25);
// 清空
dataGridView1.Rows.Clear();
六、数据绑定与实体类示例
DataGridView 最重要的用法就是绑定实体类列表,这一节重点讲。
6.1 什么是实体类(Model)
// 定义"学生"实体类
public class Student
{
public int Id { get; set; } // 学号
public string Name { get; set; } // 姓名
public int Age { get; set; } // 年龄
public string Sex { get; set; } // 性别
}
如果对
class、List<T>不熟,先看 00-CSharp基础.md。
6.2 如何新建一个实体类
方式 1:用 Visual Studio 添加类(推荐)
- 在"解决方案资源管理器"里,右键点击项目名。
- 选择"添加" → "新建项"(或"类")。
- 选择"类",文件名填
Student.cs。 - 点"添加",把上面的代码填进去。
方式 2:手动写代码
在任意 .cs 文件里(namespace 里面)粘贴上面的类代码即可。
6.3 绑定实体类列表(最简单)
private void Form1_Load(object sender, EventArgs e)
{
// 1. 准备学生列表
List<Student> students = new List<Student>
{
new Student { Id = 1, Name = "张三", Age = 25, Sex = "男" },
new Student { Id = 2, Name = "李四", Age = 22, Sex = "女" },
new Student { Id = 3, Name = "王五", Age = 28, Sex = "男" },
};
// 2. 配置表格
dataGridView1.AutoGenerateColumns = true; // 自动生成列
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 整行选中
dataGridView1.AllowUserToAddRows = false; // 隐藏新增行
dataGridView1.ReadOnly = true; // 只读
// 3. 绑定数据(表格会自动根据 Student 的属性生成列)
dataGridView1.DataSource = students;
}
6.4 手动定义列(更灵活)
private void Form1_Load(object sender, EventArgs e)
{
// 1. 关闭自动生成列
dataGridView1.AutoGenerateColumns = false;
// 2. 手动添加列,每列的 DataPropertyName 对应实体类属性名
dataGridView1.Columns.Add("Id", "学号"); // 列名, 显示标题
dataGridView1.Columns["Id"].DataPropertyName = "Id"; // 绑定实体类的 Id 属性
dataGridView1.Columns.Add("Name", "姓名");
dataGridView1.Columns["Name"].DataPropertyName = "Name";
dataGridView1.Columns.Add("Age", "年龄");
dataGridView1.Columns["Age"].DataPropertyName = "Age";
// 3. 绑定数据
dataGridView1.DataSource = students;
}
6.5 获取选中行的实体类对象
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
// 判断是否有当前行
if (dataGridView1.CurrentRow == null) return;
// 方式1:从 DataBoundItem 取出绑定的对象
Student student = dataGridView1.CurrentRow.DataBoundItem as Student;
if (student != null)
{
MessageBox.Show($"选中:{student.Name},年龄:{student.Age}");
}
}
6.6 获取选中行的某个单元格值
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0) return; // 点击列头时不处理
// 通过列名取单元格值
object name = dataGridView1.Rows[e.RowIndex].Cells["Name"].Value;
object age = dataGridView1.Rows[e.RowIndex].Cells["Age"].Value;
MessageBox.Show($"姓名:{name},年龄:{age}");
}
6.7 刷新数据(重新绑定)
private void btnRefresh_Click(object sender, EventArgs e)
{
// 重新查询数据后,重新绑定
List<Student> newList = GetStudentsFromDatabase();
dataGridView1.DataSource = null; // 先清空
dataGridView1.DataSource = newList; // 再绑定新数据
}
七、完整实战示例
做一个"学生管理"表格,选中行显示详情,隔行变色:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// 配置表格
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.ReadOnly = true;
dataGridView1.RowHeadersVisible = false;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
// 隔行变色
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
}
private void Form1_Load(object sender, EventArgs e)
{
// 加载数据
List<Student> students = new List<Student>
{
new Student { Id = 1, Name = "张三", Age = 25, Sex = "男" },
new Student { Id = 2, Name = "李四", Age = 22, Sex = "女" },
new Student { Id = 3, Name = "王五", Age = 28, Sex = "男" },
new Student { Id = 4, Name = "赵六", Age = 30, Sex = "女" },
};
dataGridView1.DataSource = students;
}
// 选中行时显示详情
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow == null) return;
// 取出绑定的对象
Student student = dataGridView1.CurrentRow.DataBoundItem as Student;
if (student != null)
{
lblDetail.Text = $"学号:{student.Id},姓名:{student.Name},年龄:{student.Age},性别:{student.Sex}";
}
}
}
// 学生实体类
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
}
八、常见问题
Q1:怎么绑定数据?
答:dataGridView1.DataSource = 对象列表或 DataTable;
Q2:怎么让表格只读、不能编辑?
答:dataGridView1.ReadOnly = true;
Q3:怎么隐藏底部新增空行?
答:dataGridView1.AllowUserToAddRows = false;
Q4:怎么获取选中行的对象?
答:dataGridView1.CurrentRow.DataBoundItem as 类型;
Q5:怎么隔行变色?
答:设置 AlternatingRowsDefaultCellStyle.BackColor。
Q6:怎么让列自动填满表格?
答:dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;