How to change 'sort glyph icon' color in DataGridView of Windows Form C#?

跟風遠走 提交于 2019-12-11 07:39:12

问题


I've changed the column header color by default. Now, I want to change the 'sort glyph icon' color in DataGridView of Windows Form C# when it gets sorted:

See the above picture. The column is sorted but icon's color makes it's visibility inadequate.

Please let me know if it's color can be changed. Thanks!


回答1:


There is no property for changing color of sort icon. As an option to change it, you can handle CellPainting event and draw the cell yourself.

Example

private void dgv1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    var grid = (DataGridView)sender;
    var sortIconColor = Color.Red;
    if (e.RowIndex == -1 && e.ColumnIndex > -1)
    {
        using (var b = new SolidBrush(BackColor))
        {
            //Draw Background
            e.PaintBackground(e.CellBounds, false);

            //Draw Text Default
            //e.Paint(e.CellBounds, DataGridViewPaintParts.ContentForeground);

            //Draw Text Custom
            TextRenderer.DrawText(e.Graphics, string.Format("{0}", e.FormattedValue),
                e.CellStyle.Font, e.CellBounds, e.CellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Left);

            //Draw Sort Icon
            if (grid.SortedColumn?.Index == e.ColumnIndex)
            {
                var sortIcon = grid.SortOrder == SortOrder.Ascending ? "▲":"▼";

                //Or draw an icon here.
                TextRenderer.DrawText(e.Graphics, sortIcon,
                    e.CellStyle.Font, e.CellBounds, sortIconColor,
                    TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            }

            //Prevent Default Paint
            e.Handled = true;
        }
    }
}

Draw Visual Styles Sort Icon

To see drawing with Visual Styles sort icon, take a look at this post.



来源:https://stackoverflow.com/questions/47261331/how-to-change-sort-glyph-icon-color-in-datagridview-of-windows-form-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!