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
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);