我刚开始使用 .NET 和 C#,我必须从模型中实现一个表。 我正在使用 winform,但我遇到了有关表头的问题。
我不知道如何在单元格中创建包含两行和 5 列的标题。
你能给我解释一下如何实现吗? 非常感谢!
编辑:您能告诉我如何将复选框也放入单元格吗?
编辑 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 类型即可。
关于c# - 在 .NET winform 中重现表格模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32398832/