如何在DataGridView中显示客户名称而非client_id字段值
实现方案
这里提供三种常用的实现方式,可根据你的业务场景选择:
方案1:使用DataRelation + 计算列(最推荐,支持后续数据编辑)
这个方案不需要修改原有表数据,也不用重查数据库,仅在内存中完成关联:
- 首先为两个DataTable建立关联关系
- 在requests表中新增计算列,直接关联clients表的name字段
- 隐藏原有的client_id列即可
代码示例:
// 1. 先确保两个DataTable在同一个DataSet中,如果没有就先加进去 DataSet ds = new DataSet(); ds.Tables.Add(clientsDataTable); ds.Tables.Add(requestsDataTable); // 2. 建立主外键关系:clients.id是主键,requests.client_id是外键 DataRelation relClientRequest = new DataRelation( "ClientRequestRel", ds.Tables["clients"].Columns["id"], ds.Tables["requests"].Columns["client_id"] ); ds.Relations.Add(relClientRequest); // 3. 给requests表新增计算列,直接取关联的父表name字段 requestsDataTable.Columns.Add("客户名称", typeof(string), "Parent(ClientRequestRel).name"); // 4. 绑定数据后隐藏原来的client_id列(可选) _requestsDataGridView.DataSource = requestsDataTable; _requestsDataGridView.Columns["client_id"].Visible = false;
方案2:使用CellFormatting事件(适合小数据量场景)
如果你的数据量不大(千条以内),可以直接处理DataGridView的CellFormatting事件,动态转换ID为名称:
// 先订阅事件,一般放在窗体初始化逻辑里 _requestsDataGridView.CellFormatting += _requestsDataGridView_CellFormatting; // 事件处理逻辑 private void _requestsDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { // 只处理client_id列,注意替换成你自己的列索引或者列名 if (e.ColumnIndex == _requestsDataGridView.Columns["client_id"].Index && e.RowIndex >= 0) { int clientId = Convert.ToInt32(e.Value); // 去clients表查询对应name DataRow[] rows = clientsDataTable.Select($"id = {clientId}"); if (rows.Length > 0) { e.Value = rows[0]["name"].ToString(); e.FormattingApplied = true; } } }
方案3:提前关联两张表生成新数据源(适合仅展示不需要编辑的场景)
如果你的DataGridView只做展示不需要编辑数据,可以直接用LINQ关联两个表生成新的数据源绑定:
var query = from req in requestsDataTable.AsEnumerable() join client in clientsDataTable.AsEnumerable() on req.Field<int>("client_id") equals client.Field<int>("id") select new { 请求ID = req.Field<int>("id"), 请求日期 = req.Field<int>("date"), 客户名称 = client.Field<string>("name"), // 其他你需要展示的字段 }; _requestsDataGridView.DataSource = query.ToList();
内容的提问来源于stack exchange,提问作者Aimon Z.
相关产品推荐
相关产品推荐

