Net Core 7 WinForms中如何正确关联DataGridView显示关联行?
问题分析与解决方案
你的代码中dataGridView2无法正常显示数据的核心原因是:绑定的数据源是包含List
修复步骤
1. 优化DataGridView1的选中模式
在MainForm_Load方法中添加选中模式设置,确保整行选中:
private void MainForm_Load(object sender, EventArgs e) { dataGridView1.DataSource = InitialData.ListPerson; dataGridView1.MultiSelect = false; // 设置整行选中模式 dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView1.Rows[0].Selected = true; }
2. 修正关联数据绑定逻辑
修改dataGridView1_RowEnter事件,直接获取选中的Person对象,并根据需要绑定对应的关联集合:
场景1:显示地址列表(Adr)
Adr是实体类列表,可直接绑定到dataGridView2,DataGridView会自动识别实体的属性列:
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e) { if (dataGridView1.SelectedRows.Count != 1) return; // 直接获取选中行绑定的Person对象 var selectedPerson = dataGridView1.SelectedRows[0].DataBoundItem as Person; if (selectedPerson == null) return; // 绑定地址列表到dataGridView2 dataGridView2.DataSource = selectedPerson.Adr; }
场景2:显示电话/邮箱列表
Telephonе和Email是List
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e) { if (dataGridView1.SelectedRows.Count != 1) return; var selectedPerson = dataGridView1.SelectedRows[0].DataBoundItem as Person; if (selectedPerson == null) return; // 显示电话列表(转换为带列名的对象列表) dataGridView2.DataSource = selectedPerson.Telephonе.Select(t => new { 联系电话 = t }).ToList(); // 如果要显示邮箱列表,替换为下面的代码 // dataGridView2.DataSource = selectedPerson.Email.Select(m => new { 邮箱地址 = m }).ToList(); }
场景3:同时显示电话和邮箱
如果需要在dataGridView2中同时展示电话和邮箱,可以构造包含两者的对象(处理数量不一致的补全逻辑):
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e) { if (dataGridView1.SelectedRows.Count != 1) return; var selectedPerson = dataGridView1.SelectedRows[0].DataBoundItem as Person; if (selectedPerson == null) return; // 处理电话和邮箱数量不一致的情况,取最大长度补全空值 int maxCount = Math.Max(selectedPerson.Telephonе.Count, selectedPerson.Email.Count); var combinedData = Enumerable.Range(0, maxCount) .Select(i => new { 联系电话 = i < selectedPerson.Telephonе.Count ? selectedPerson.Telephonе[i] : string.Empty, 邮箱地址 = i < selectedPerson.Email.Count ? selectedPerson.Email[i] : string.Empty }) .ToList(); dataGridView2.DataSource = combinedData; }
额外说明
- 如果需要自定义DataGridView的列(比如修改列名、隐藏列),可以在设计器中手动添加列并设置
DataPropertyName对应实体的属性名,或者通过代码动态创建列。 - 若要使用BindingSource进行绑定(更灵活支持数据更新),可以将集合包装到BindingSource中,例如:
var adrBindingSource = new BindingSource(); adrBindingSource.DataSource = selectedPerson.Adr; dataGridView2.DataSource = adrBindingSource;
内容的提问来源于stack exchange,提问作者Anton
相关产品推荐
相关产品推荐

