Remove sorting arrow in datagridview header and put the text in the center of the box

后端 未结 1 1098
时光说笑
时光说笑 2021-01-13 19:28

I am working on a project which required header text to be in the center, and when click the header it will do the sorting. But the problem is, there is a sorting arrow icon

1条回答
  •  借酒劲吻你
    2021-01-13 19:48

    For aligning column header text at the middle, you can rely on DataGridView properties. But for custom sort icon, you need custom paint.

    To set column header text alignment:

    • Set Alignment property of the ColumnHeadersDefaultCellStyle to MiddleCenter.

    To paint custom sort icon:

    • Handle the CellPainting event and check if we are painting the header:

      if (e.RowIndex == -1) //It's header cell
      
    • Paint cell background

      e.PaintBackground(e.CellBounds, false);
      
    • Paint content foreground (text):

      e.Paint(e.CellBounds, DataGridViewPaintParts.ContentForeground);
      
    • Paint custom sort glyph using DrawImage or by drawing a suitable character:

      if (grid.SortedColumn?.Index == e.ColumnIndex)
      {
          var sortIcon = grid.SortOrder == SortOrder.Ascending ? "▲":"▼";
      
          //Just for example I rendered a character, you can draw an image.
          TextRenderer.DrawText(e.Graphics, sortIcon,
              e.CellStyle.Font, e.CellBounds, sortIconColor,
              TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
      }
      
    • Stop default paint

      e.Handled = true;
      

    Note - Draw Visual Styles Sort Icon

    • If you wanted to draw default sort icon:

      e.Paint(e.CellBounds, DataGridViewPaintParts.ContentBackground);
      
    • Just as an example, drawing visual style sort icon:

      if (grid.SortedColumn?.Index == e.ColumnIndex)
      {
          var sortIcon = grid.SortOrder == SortOrder.Ascending ?
              VisualStyleElement.Header.SortArrow.SortedUp : 
              VisualStyleElement.Header.SortArrow.SortedDown;
          var renderer = new VisualStyleRenderer(sortIcon);
          var size = renderer.GetPartSize(e.Graphics, ThemeSizeType.Draw);
          renderer.DrawBackground(e.Graphics,
              new Rectangle(e.CellBounds.Right - size.Width,
              e.CellBounds.Top, size.Width, e.CellBounds.Height));
      }
      

    0 讨论(0)
提交回复
热议问题