C#中的DataGridView应用
DataGridView是Windows Forms中用于显示和编辑表格数据的核心控件。以下是关键应用场景和实现方法:
1. 基础数据绑定
// 创建数据表并绑定
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Rows.Add(1, "张三");
table.Rows.Add(2, "李四");
dataGridView1.DataSource = table; // 绑定到控件
2. 列自定义
// 手动添加列(自动生成列设为false)
dataGridView1.AutoGenerateColumns = false;
// 添加文本列
DataGridViewTextBoxColumn colId = new DataGridViewTextBoxColumn();
colId.HeaderText = "员工ID";
colId.DataPropertyName = "ID";
dataGridView1.Columns.Add(colId);
// 添加按钮列
DataGridViewButtonColumn btnCol = new DataGridViewButtonColumn();
btnCol.Text = "操作";
btnCol.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(btnCol);
3. 事件处理
常用事件及处理:
// 单元格点击事件
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1 && e.RowIndex >= 0) // 按钮列索引
{
MessageBox.Show($"点击了行: {e.RowIndex}");
}
}
// 数据验证
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 0) // ID列
{
if (!int.TryParse(e.FormattedValue.ToString(), out _))
{
MessageBox.Show("ID必须为数字!");
e.Cancel = true;
}
}
}
4. 样式定制
// 交替行颜色
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
// 设置列宽
dataGridView1.Columns[0].Width = 80;
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
// 冻结首列
dataGridView1.Columns[0].Frozen = true;
5. 数据操作
// 添加新行
DataRow newRow = ((DataTable)dataGridView1.DataSource).NewRow();
newRow["ID"] = 3;
newRow["Name"] = "王五";
((DataTable)dataGridView1.DataSource).Rows.Add(newRow);
// 删除选中行
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
if (!row.IsNewRow) dataGridView1.Rows.Remove(row);
}
6. 高级功能
- 数据过滤:通过BindingSource实现
BindingSource source = new BindingSource(); source.DataSource = dataTable; source.Filter = "ID > 1"; dataGridView1.DataSource = source; - 单元格格式化:显示图标/进度条
DataGridViewProgressColumn progressCol = new DataGridViewProgressColumn(); dataGridView1.Columns.Add(progressCol);
注意事项
- 大数据量时启用虚拟模式(
VirtualMode=true) - 通过
BeginEdit()和EndEdit()控制编辑状态 - 使用
BindingList<T>替代DataTable实现实时更新
示例:创建带排序和过滤的员工表
完整项目参考:MSDN DataGridView文档
C#中DataGridView的应用

1万+

被折叠的 条评论
为什么被折叠?



