先上效果图。
对外提供一个 public 的方法:
// 正常 Type1 是 JSON 的数据集或者 BSON 的数据集
public void FillDataGridView(Type1 data, DataGridView gridView){
// 为 gridView 添加字段
...
// 为 gridView 添加数据
foreach(Type2 d in data){
if(d 是复杂的数据类型){
// 创建子 DataGridview
// 属性根据自己的需要设定
DataGridView view = new DataGridView();
view.AllowUserToAddRows = false;
view.AllowUserToDeleteRows = false;
view.AllowUserToOrderColumns = false;
view.BackgroundColor = System.Drawing.Color.White;
view.ReadOnly = true;
view.Visible = false;
// 此处递归调用,使得数据中所有的复杂数据类型都能用 DataGridview 单独显示出来
FillDataGridView(d as Type1, view);// 或者 FillDataGridView(new Type1(d), view);
// 设置当前的 cell
DataGridViewCell cell = ...;
// 设置子 DataGridview 的位置
view.Parent = gridView;
// 以下这种方法,需要单元格都是等长等宽才能有好的效果
view.Left = gridView.Left + gridView.RowHeadersWidth + gridView.Columns[0].Width * cell.ColumnIndex;
view.Top = gridView.Top + gridView.ColumnHeadersHeight + gridView.Rows[0].Height * cell.RowIndex;
// 为当前的 DataGridview 以及子 DataGridview 设置响应事件
// 以至于达到我们想要的效果:点击 cell 用另外一个 DataGridview 显示出该 cell 中的数据
// 接下来有两个响应方法,在这个方法的后面,往下翻就有了
gridView.CellClick += GridViewCellClick;
view.CellClick += GridViewCellClick;
view.Leave += GridViewLeave;
// 最后将 cell 和子 DataGridview 绑定起来
cell.Tag = view;
cell.value = "点击查看";
}
else{
// 向 cell 中填入数据
...
}
}
}
private void GridViewCellClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCell cell = (sender as DataGridView).CurrentCell;
if (cell.Tag != null && cell.Tag is DataGridView)
{
DataGridView view = (cell.Tag as DataGridView);
view.Visible = true;
// 此处让 view 获得焦点时为了给 GridViewLeave 提供方便
// 如果此处不加 Focus 的话,就需要先点击 view 然后点击其他控件来让 view 失去焦点
// 此时 view 才会消失,可是这样子的体验非常差
view.Focus();
}
}
private void GridViewLeave(object sender, EventArgs e)
{
(sender as DataGridView).Visible = false;
}
OK.
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有