DataGridView替换岗位编号为名称及指定列绑定报错问题咨询
解决方案
一、解决指定DataTable列名报错的问题
指定列名时报错,核心原因是ObjectReader.Create传入的列名和Employee实体类的属性名不匹配(比如大小写差异、拼写错误,或者实体类中对应的属性是JobClassId而非jobClass)。
修复步骤
- 核对
Employee实体类的属性名称,确保传入的字符串和实体属性名完全一致。比如实体类定义如下:
public class Employee { public int ID { get; set; } public string Name { get; set; } public int JobClassId { get; set; } public string College { get; set; } public string Department { get; set; } }
那你需要把"jobClass"改成"JobClassId",和实体属性名对应。
- 若不想依赖
ObjectReader,可以手动构建DataTable,避免属性名匹配问题:
DataTable employeesTable = new DataTable(); // 手动添加对应列 employeesTable.Columns.Add("ID", typeof(int)); employeesTable.Columns.Add("姓名", typeof(string)); employeesTable.Columns.Add("岗位类别", typeof(string)); employeesTable.Columns.Add("院校", typeof(string)); employeesTable.Columns.Add("部门", typeof(string)); // 遍历列表填充数据 foreach (var emp in employeesList) { employeesTable.Rows.Add(emp.ID, emp.Name, emp.JobClassId, emp.College, emp.Department); } dgvEmployees.DataSource = employeesTable;
二、替换岗位编号为名称的两种实现方式
方式1:EF关联查询(推荐,性能更优)
直接利用EF的关联查询,在获取员工数据时同时取出岗位名称,无需后续二次查询:
// 假设Employee和JobClass是一对多关联,Employee包含JobClass导航属性 var employeesList = db.EmployeeRepository.GetAllEmployees() .Include(e => e.JobClass) // 关联岗位表 .Select(e => new { e.ID, e.Name, 岗位类别 = e.JobClass.Name, // 直接映射岗位名称 e.College, e.Department }) .ToList(); // 直接绑定匿名列表到DataGridView,无需转DataTable dgvEmployees.DataSource = employeesList;
方式2:字典映射(适合无关联查询场景)
先批量获取所有岗位数据存入字典,再遍历员工列表替换编号:
// 一次性获取所有岗位,避免循环内多次查库 var jobClassDict = db.JobClassRepository.GetAll().ToDictionary(jc => jc.Id, jc => jc.Name); DataTable employeesTable = new DataTable(); employeesTable.Columns.Add("ID", typeof(int)); employeesTable.Columns.Add("姓名", typeof(string)); employeesTable.Columns.Add("岗位类别", typeof(string)); employeesTable.Columns.Add("院校", typeof(string)); employeesTable.Columns.Add("部门", typeof(string)); foreach (var emp in employeesList) { // 从字典中匹配岗位名称,无匹配时显示默认值 string jobName = jobClassDict.ContainsKey(emp.JobClassId) ? jobClassDict[emp.JobClassId] : "未知岗位"; employeesTable.Rows.Add(emp.ID, emp.Name, jobName, emp.College, emp.Department); } dgvEmployees.DataSource = employeesTable;
三、关于DataTable转换的必要性
除非你有特殊的DataTable操作需求,否则完全可以跳过DataTable转换,直接将EF查询后的列表(包括匿名类型列表)绑定到DataGridView,控件会自动识别列和数据,减少不必要的转换开销。
内容的提问来源于stack exchange,提问作者Elia
相关产品推荐
相关产品推荐

