You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForm实现DataGridView按手机号统计客户发票总数

实现DataGridView按手机号显示对应发票总数

方法一:数据源绑定前预处理(推荐)

如果你的客户数据和发票数据来自数据库,直接在查询阶段完成统计是最高效的方式:

  • 假设存在Customers表(包含客户姓名、手机号字段)和Invoices表(包含关联手机号、发票ID字段),可以用分组查询一次性获取统计结果:
SELECT c.CustomerName, c.PhoneNumber, COUNT(i.InvoiceId) AS TotalDueAmount
FROM Customers c
LEFT JOIN Invoices i ON c.PhoneNumber = i.PhoneNumber
GROUP BY c.CustomerName, c.PhoneNumber
  • 将查询结果直接绑定到DataGridView:
DataTable customerStats = new DataTable();
using (SqlConnection conn = new SqlConnection("你的数据库连接字符串"))
{
    string query = @"SELECT c.CustomerName, c.PhoneNumber, COUNT(i.InvoiceId) AS TotalDueAmount
                     FROM Customers c
                     LEFT JOIN Invoices i ON c.PhoneNumber = i.PhoneNumber
                     GROUP BY c.CustomerName, c.PhoneNumber";
    SqlDataAdapter adapter = new SqlDataAdapter(query, conn);
    adapter.Fill(customerStats);
}
dataGridView1.DataSource = customerStats;

方法二:已绑定数据源后逐行计算

如果客户数据已经在DataGridView中,可通过内存分组统计后逐行赋值:

  • 先将发票数据按手机号分组,存入字典实现快速查找:
// 假设你有发票集合List<Invoice> invoices,Invoice类包含PhoneNumber属性
Dictionary<string, int> invoiceCountMap = invoices
    .GroupBy(inv => inv.PhoneNumber)
    .ToDictionary(group => group.Key, group => group.Count());
  • 遍历DataGridView行,根据手机号匹配统计值:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.IsNewRow) continue; // 跳过新增空白行

    string phone = row.Cells["手机号"].Value.ToString();
    // 无匹配手机号时显示0
    row.Cells["Total Due Amount"].Value = invoiceCountMap.TryGetValue(phone, out int count) ? count : 0;
}

注意事项

  • 确保「Total Due Amount」列的ValueType设置为int,避免显示格式异常。
  • 若发票数据会动态更新,需在数据变更后重新执行统计赋值逻辑。

内容的提问来源于stack exchange,提问作者Mutaz Adil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:35:21