我只是从.NET和C#开始,我必须从模型中实现一个表.
我正在使用winform,但我遇到了关于表头的问题.
我不知道如何在单元格中创建一个包含两行和五列的标题.
你可以向我解释一下如何实现它吗?
非常感谢 !
编辑:你告诉我怎么把复选框放在单元格中?
编辑2:我点什么.
代码几乎是空的,与我想要实现的GUI没有任何联系.
最佳答案 使用CellPainting事件是可行的:
dgv.CellPainting += dgv_CellPainting;
void dgv_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
if (e.ColumnIndex > -1 && e.RowIndex == -1) {
if (e.ColumnIndex == 1) {
int totalWidth = e.CellBounds.Width;
for (int i = 2; i < 5; ++i) {
totalWidth += dgv.Columns[i].Width;
}
Rectangle r = new Rectangle(e.CellBounds.Left, e.CellBounds.Top + 1,
totalWidth, e.CellBounds.Height - 16);
e.Graphics.FillRectangle(Brushes.LightGray, r);
TextRenderer.DrawText(e.Graphics, "IMPORT SITES", SystemFonts.DefaultFont,
new Rectangle(r.Left, r.Top, r.Width, r.Height - 4),
Color.Black, Color.Empty,
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
e.Graphics.DrawRectangle(Pens.Gray, new Rectangle(r.Left - 1, r.Top - 1, r.Width, r.Height));
}
if (e.ColumnIndex >= 1 && e.ColumnIndex <= 4) {
Rectangle r = new Rectangle(e.CellBounds.Left, e.CellBounds.Top + e.CellBounds.Height - 16,
e.CellBounds.Width, 16);
e.Graphics.FillRectangle(Brushes.LightGray, r);
TextRenderer.DrawText(e.Graphics, dgv.Columns[e.ColumnIndex].HeaderText,
SystemFonts.DefaultFont, new Rectangle(r.Location, new Size(r.Width, r.Height - 2)),
Color.Black, Color.Empty, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
e.Graphics.DrawRectangle(Pens.Gray, new Rectangle(r.Left - 1, r.Top - 1, r.Width, r.Height));
} else {
e.Graphics.FillRectangle(Brushes.LightGray, e.CellBounds);
TextRenderer.DrawText(e.Graphics, dgv.Columns[e.ColumnIndex].HeaderText,
SystemFonts.DefaultFont, e.CellBounds, Color.Black, Color.Empty,
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
e.Graphics.DrawRectangle(Pens.Gray, new Rectangle(e.CellBounds.Left - 1, e.CellBounds.Top,
e.CellBounds.Width, e.CellBounds.Height - 1));
}
e.Handled = true;
}
}
结果(根据需要调整):
对于复选框,只需使用编辑器添加DataGridViewCheckBoxColumn类型.