我正在使用DataGridView来填充来自数据库的数据。我有两种“类型”的行,一种是父行,另一种是子行。我希望孩子是左缩进,所以它将不得不在视觉上看“父母-孩子”的关系。
如何做到这一点?
发布于 2011-08-26 23:04:35
既然您说过可能只突出显示子行,下面是实现此目的的一些代码。您也可以只更改RowsAdded事件的背景颜色,但这种方式更整洁、更快(该行不必绘制两次)。
处理DataGridView的RowPrePaint事件:
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;
}
}实际上,我通常更喜欢使用渐变笔刷来进行特殊的突出显示:
using (Brush brush = new LinearGradientBrush(rowBounds, color1, color2,
LinearGradientMode.Horizontal))
{
e.Graphics.FillRectangle(brush, rowBounds);
}其中color1和color2将是您选择的任何颜色。
https://stackoverflow.com/questions/7179567
复制相似问题