Why doesn't AutoResize work for Row Header Width in DataGridView in C#?

后端 未结 1 612
庸人自扰
庸人自扰 2021-01-23 02:31

I am new at DataGridView control and it confused me so much. I have a problem in with row header width doesn\'t have a good fit to the text inside of it. I did make a search but

1条回答
  •  被撕碎了的回忆
    2021-01-23 03:05

    DataGridView calculates the preferred size of the row header by applying text width, row icon width and padding.

    To change the way which preferred size is calculated and also to prevent drawing icons, you need to create a custom row header cell inheriting DataGridViewRowHeaderCell and override GetPreferredSize and Paint methods:

    public class CustomHeaderCell : DataGridViewRowHeaderCell
    {
        protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize)
        {
            var size1 = base.GetPreferredSize(graphics, cellStyle, rowIndex, constraintSize);
            var value = string.Format("{0}", this.DataGridView.Rows[rowIndex].HeaderCell.FormattedValue);
            var size2 = TextRenderer.MeasureText(value, cellStyle.Font);
            var padding = cellStyle.Padding;
            return new Size(size2.Width + padding.Left+padding.Right, size1.Height);
        }
        protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, DataGridViewPaintParts.Background);
            base.PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
            TextRenderer.DrawText(graphics, string.Format("{0}", formattedValue), cellStyle.Font, cellBounds, cellStyle.ForeColor);
        }
    }
    

    Then it's enough to replace current header cells with your new header cell:

    //Put this lines before adding rows
    grid.RowTemplate.DefaultHeaderCellType = typeof(CustomHeaderCell);
    grid.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
    grid.RowHeadersDefaultCellStyle.Padding = new Padding(2);
    

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