CDataGridView控件增删查改实例:C# DataGridView序列号自动生成与末行显示

原创
小哥 2年前 (2025-02-08) 阅读数 185 #C#
文章标签 C#

免费下载 CDataGridView控件增删查改实例:C# DataGridView序列号自动生成与末行显示(夸克网盘,免费获取,无需注册)

资源名称CDataGridView控件增删查改实例:C# DataGridView序列号自动生成与末行显示
下载方式夸克网盘
是否免费免费
提取码无需提取码
立即免费下载

DataGridView 增删查改基本操作

DataGridView 是 C# WinForms 开发中最常用的数据表格控件,CDataGridView控件在其基础上封装了增删查改、序列号自动生成与末行显示等常用操作。本文面向使用 Visual Studio 2019/2022(兼容 .NET Framework 4.7.2 与 .NET 6/8)的开发者,通过一个仓库物料实时监控模拟实例演示完整流程。DataGridView 支持两种数据维护方式:无绑定模式直接操作行,适合小数据量场景;绑定模式配合 BindingList<T> 自动同步界面,适合需要实时刷新的业务系统,初学者可以直接跟着敲,中级开发者也能把事件处理思路迁移到自己的项目里。

CDataGridView控件增删查改实例:C# DataGridView序列号自动生成与末行显示

增加数据

无绑定模式下,调用 Rows.Add 即可追加一行:

dataGridView1.Rows.Add("M001", "内六角螺丝", 500);

绑定模式下只需向数据源添加对象,表格会自动刷新:

materials.Add(new Material { Code = "M002", Name = "平垫圈", Qty = 1200 });

删除数据

先判断 CurrentRow 是否为空,再调用 Rows.Remove:

if (dataGridView1.CurrentRow != null
    && !dataGridView1.CurrentRow.IsNewRow)
{
    dataGridView1.Rows.Remove(dataGridView1.CurrentRow);
}

注意 AllowUserToDeleteRows 属性要设为 true,否则界面上的删除操作不可用。

查询数据

简单遍历适合内存数据:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Cells["名称"].Value?.ToString().Contains("螺丝") == true)
        row.Selected = true;
}

如果绑定了 BindingSource,可以用 Filter 属性完成筛选:

bindingSource1.Filter = "名称 LIKE '%螺丝%'";

修改数据

设置 ReadOnly = false 并监听 CellEndEdit 事件,在提交前做校验:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    var cell = dataGridView1.Rows[e.RowIndex].Cells["数量"];
    if (!int.TryParse(cell.Value?.ToString(), out int qty) || qty < 0)
    {
        cell.ErrorText = "数量必须为非负整数";
        cell.Value = 0;
    }
}

自动生成序列号

在 RowsAdded 与 RowsRemoved 两个事件中统一重编号,删除中间行后序号不会断档:

private void ReIndex()
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
        if (!row.IsNewRow)
            row.Cells["序号"].Value = row.Index + 1;
}

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) => ReIndex();
private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) => ReIndex();

同时把"序号"列的 ReadOnly 设为 true,防止用户手动修改导致编号混乱。

末行显示

追加一行作为提示或合计行,并把该行各单元格设为只读:

int footerIndex = dataGridView1.Rows.Add("合计", "", totalQty);
dataGridView1.Rows[footerIndex].ReadOnly = true;
dataGridView1.Rows[footerIndex].DefaultCellStyle.BackColor = Color.LightYellow;

若要显示"无更多数据""加载更多"等提示,逻辑相同,只需替换单元格文本即可。

仓库物料实时监控模拟实例

实例在 Visual Studio 2022 + .NET Framework 4.7.2 环境下调试通过,.NET 6/8 的 WinForms 项目同样适用。新建"Windows 窗体应用(.NET Framework)"项目后,按以下步骤操作:

  1. 新建 Material 类,包含 Code、Name、Qty 三个属性。
  2. 创建 BindingList<Material> 并赋给 dataGridView1.DataSource。
  3. 放置"新增、删除、查询、修改"四个按钮,分别调用上文对应方法。
  4. 用 System.Windows.Forms.Timer 每 2 秒模拟一次入库,向列表添加随机物料,表格实时刷新。
  5. 在末行显示当前库存总量。
public class Material
{
    public string Code { get; set; }
    public string Name { get; set; }
    public int Qty { get; set; }
}

// 窗体加载时绑定
BindingList<Material> materials = new BindingList<Material>
{
    new Material { Code = "M001", Name = "螺丝", Qty = 500 }
};
dataGridView1.DataSource = materials;

// 定时器模拟实时入库
private void timer1_Tick(object sender, EventArgs e)
{
    materials.Add(new Material
    {
        Code = "M" + materials.Count.ToString("D3"),
        Name = "随机物料",
        Qty = new Random().Next(10, 200)
    });
}

下载方式见文末。

常见问题

Q1:点击删除按钮没有任何反应?

检查三个地方:AllowUserToDeleteRows 是否为 true;CurrentRow 是否为 null(未选中行时不能删除);是否误把整表 ReadOnly 设成了 true。

Q2:删除中间行后序列号出现断档?

只在 RowsAdded 里编号、没有在 RowsRemoved 里重新调用 ReIndex(),补上即可。另外注意跳过 IsNewRow 为 true 的空白新行。

Q3:运行时抛出"跨线程操作无效: 控件... accessed from a thread other than the thread it was created on"?

在 Timer 回调或后台线程中直接改 UI 数据会触发该异常。用 Invoke 切回 UI 线程:

this.Invoke(new Action(() => materials.Add(new Material { ... })));

Q4:末行合计行被当成普通数据删除了?

删除前判断行索引是否等于末行索引,或者给合计行打标记(例如在第一列存特殊值),删除逻辑中跳过该行。

注意事项

  • DataGridView 直接操作只适合千行以内数据,上万行请改用 VirtualMode 虚拟模式或分页加载。
  • 绑定模式下不要同时手动调用 Rows.Add,否则会出现数据源与界面不同步。
  • 本文示例仅用于学习,代码可自由用于个人项目,转载请注明出处。

下载地址

以上资源由网络收集整理,版权归原作者及软件厂商所有,请在授权范围内使用;如涉及侵权请联系本站删除。

常见问题

这个资源需要付费吗?不需要,本文提供的资源可免费获取。

下载需要注册网盘账号吗?不需要注册,打开网盘链接即可保存或下载。

有提取码吗?无需提取码,打开网盘链接即可转存或下载。

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除