首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更改DataGridViewRow的左填充

更改DataGridViewRow的左填充
EN

Stack Overflow用户
提问于 2011-08-25 01:16:07
回答 1查看 477关注 0票数 1

我正在使用DataGridView来填充来自数据库的数据。我有两种“类型”的行,一种是父行,另一种是子行。我希望孩子是左缩进,所以它将不得不在视觉上看“父母-孩子”的关系。

如何做到这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-08-26 23:04:35

既然您说过可能只突出显示子行,下面是实现此目的的一些代码。您也可以只更改RowsAdded事件的背景颜色,但这种方式更整洁、更快(该行不必绘制两次)。

处理DataGridView的RowPrePaint事件:

代码语言:javascript
复制
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;     
    }   
}

实际上,我通常更喜欢使用渐变笔刷来进行特殊的突出显示:

代码语言:javascript
复制
using (Brush brush = new LinearGradientBrush(rowBounds, color1, color2,  
       LinearGradientMode.Horizontal))
{
    e.Graphics.FillRectangle(brush, rowBounds);
}

其中color1color2将是您选择的任何颜色。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7179567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档