Reputation: 1590
I want to create a gridView in WinForms, that is able to obtain columns containing subcolumns. Row elements should be able to fill multiple rows.
This is an example code
public partial class Frm : Form
{
public Frm()
{
InitializeComponent();
gridView.DataSource = FillTable(); // set the table
}
private DataTable FillTable() // set some example data
{
DataTable tbl = new DataTable();
tbl.Columns.Add("Col 1", typeof(int));
tbl.Columns.Add("Col 2", typeof(string));
tbl.Columns.Add("Col 3", typeof(bool));
tbl.Rows.Add(1, "Val 1", true);
tbl.Rows.Add(2, "Val 2", false);
tbl.Rows.Add(3, "Val 3", true);
tbl.Rows.Add(4, "Val 4", false);
tbl.Rows.Add(5, "Val 5", true);
return tbl;
}
}
And this code results in
so what I want is something like this
Some rows or columns should be bigger than "having a cell size of 1,1".
Is it possible to obtain this by code? Painting a grid wouldn't be the best solution, when resizing a column or something like that.
Upvotes: 0
Views: 329
Reputation: 30512
I think the easiest solution is two create two subclasses of DataGridViewRowHeaderCell.
The NoPaintHeaderCell is a DataGridViewHeaderCell that is like any other DataGridViewHeaderCell, but does not paint anything.
The MultiColumnHeaderCell is a DataGridViewHeaderCell that paints all Headers starting at the location of the cell, inclusive all NoPaintHeaderCells that are on the right side of the MultiColumnHeaderCell
In your example column 2 would get a MultiColumnHeaderCell and column 3 a NoPaintHeaderCell. When the MultiColumnHeaderCell of column 2 needs to be painted, it detects which kind of header cells are on the right of it. Then it decides to paint all cells as if it was one big cell.
So MultiColumnHeaderCell overrides DataGridViewHeaderCell.Paint
protected override void Paint(Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates dataGridViewElementState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
// adjust clipbounds and cellbounds, such that it paints itself +
// the area of the NoPaintCells directly on the right.
base.Paint(adjustedClipBounds, adjustedCellBounds, ...);
}
See the source code of DataGridViewHeaderCell.Paint. You'll see a code snippet:
if (DataGridViewCell.PaintBorder(paintParts))
{
PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
}
Because you adjusted the clipBounds and the cellBounds you don't have to override DataGridViewCellHeader.PaintBorder
The NoPaintHeaderCell does not do anything when it paints.
Upvotes: 2