Reputation: 8020
I am using a DataGridView to populate the data from a database. I have two "types" of rows, one displays parent, and second displays children. I would like the children to be left-indented so it will have to visual look of a "parent-children" relationship.
How can this be done?
Upvotes: 1
Views: 523
Reputation: 16747
Since you said you might just highlight child rows, here's some code to do that. You could also just change the backcolor on the RowsAdded event, but this way is neater and faster (the row doesn't have to be painted twice).
Handle the DataGridView's RowPrePaint event:
private void dataGrid_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
// use whatever your row data type is here
MyDataType item = (MyDataType)(dataGrid.Rows[e.RowIndex].DataBoundItem);
// only highlight children
if (item.parentID != 0)
{
// calculate the bounds of the row
Rectangle rowBounds = new Rectangle(
dataGrid.RowHeadersVisible ? dataGrid.RowHeadersWidth : 0, // left
e.RowBounds.Top, // top
dataGrid.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - dataGrid.HorizontalScrollingOffset + 1, // width
e.RowBounds.Height // height
);
// if the row is selected, use default highlight color
if (dataGrid.Rows[e.RowIndex].Selected)
{
using (Brush brush = new SolidBrush(dataGrid.DefaultCellStyle.SelectionBackColor))
e.Graphics.FillRectangle(brush, rowBounds);
}
else // otherwise use a special color
e.Graphics.FillRectangle(Brushes.PowderBlue, rowBounds);
// prevent background from being painted by Paint method
e.PaintParts &= ~DataGridViewPaintParts.Background;
}
}
I actually usually prefer to use a gradient brush for special highlighting:
using (Brush brush = new LinearGradientBrush(rowBounds, color1, color2,
LinearGradientMode.Horizontal))
{
e.Graphics.FillRectangle(brush, rowBounds);
}
Where color1
and color2
would be whatever colors you choose.
Upvotes: 1