Windows Form中如何在DataGridView显示List<string>类型属性
问题原因
WinForm 的 DataGridView 控件默认自动生成列时,仅会对字符串、数值、日期等简单类型的属性创建展示列,List<T> 等集合类型属性没有默认的展示逻辑,所以会被自动跳过。
解决方案
这里提供3种常用的适配方案,你可以根据自己的业务需求选择:
方案1:新增格式化展示属性(最简便)
直接在 Department 类中新增只读属性,将集合转为格式化后的字符串供绑定使用:
public class Department { // 原有属性保持不变,给不需要自动展示的集合属性加[Browsable(false)]标记 public int DNumber { get; set; } public string DName { get; set; } [System.ComponentModel.Browsable(false)] public List<string> Locations { get; set; } [System.ComponentModel.Browsable(false)] public List<Employee> Employees { get; set; } public Employee Manager { get; set; } [System.ComponentModel.Browsable(false)] public List<Project> Projects { get; set; } public string MgrStartDate { get; set; } // 新增绑定用的格式化属性 public string 位置列表 => Locations != null ? string.Join("、", Locations) : "无"; public int 员工数量 => Employees?.Count ?? 0; public int 项目数量 => Projects?.Count ?? 0; }
修改完成后重新绑定即可自动生成对应的展示列。如果需要修改集合后自动刷新展示,给类实现 INotifyPropertyChanged 接口,集合修改时触发对应展示属性的变更通知即可。
方案2:手动配置列+自定义格式化
如果不想修改实体类,可以关闭自动生成列,手动定义列并处理单元格格式化逻辑:
首先在窗体加载时配置DataGridView:
private void Form_Department_Load(object sender, EventArgs e) { Database.DbFileName = "Database.yap"; db = Database.Db; // 关闭自动生成列,手动配置列 dataGridView_Department.AutoGenerateColumns = false; dataGridView_Department.Columns.AddRange(new DataGridViewColumn[] { new DataGridViewTextBoxColumn(){ Name = "DNumber", DataPropertyName = "DNumber", HeaderText = "部门编号" }, new DataGridViewTextBoxColumn(){ Name = "DName", DataPropertyName = "DName", HeaderText = "部门名称" }, new DataGridViewTextBoxColumn(){ Name = "Locations", HeaderText = "部门位置" }, new DataGridViewTextBoxColumn(){ Name = "MgrStartDate", DataPropertyName = "MgrStartDate", HeaderText = "经理上任时间" }, new DataGridViewTextBoxColumn(){ Name = "EmployeeCount", HeaderText = "员工数量" } }); // 绑定单元格格式化事件 dataGridView_Department.CellFormatting += DataGridView_Department_CellFormatting; loadDepartment(); }
然后实现格式化事件:
private void DataGridView_Department_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (dataGridView_Department.Rows[e.RowIndex].DataBoundItem is Department dept) { if (e.ColumnIndex == dataGridView_Department.Columns["Locations"].Index) { e.Value = dept.Locations != null ? string.Join("、", dept.Locations) : "无"; e.FormattingApplied = true; } else if (e.ColumnIndex == dataGridView_Department.Columns["EmployeeCount"].Index) { e.Value = dept.Employees?.Count ?? 0; e.FormattingApplied = true; } } }
方案3:主从表布局(适合集合内容较多的场景)
如果需要完整展示集合内的所有字段,比如员工的姓名、工号等,可以用主从关联布局:
- 上方DataGridView展示部门的基础信息
- 下方放2个单独的DataGridView,分别绑定选中部门的
Locations、Employees集合 - 处理部门DataGridView的
SelectionChanged事件,选中部门后同步刷新下方集合的数据源即可
内容的提问来源于stack exchange,提问作者Nhật Đoàn
相关产品推荐
相关产品推荐

