I am trying to override the DataGridViewTextBoxCell’s paint method in a derived class so that I can indent the foreground text by some variable amount of pixels. I would like it if the width of the column adjusts so that its total width is the length of my cells text plus the ‘buffer’ indent. Does anyone know of a way to accomplish this? My lame implementation is listed below:
public class MyTextBoxCell : DataGridViewTextBoxCell{ .... 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) { clipBounds.Inflate(100, 0); DataGridViewPaintParts pp = DataGridViewPaintParts.Background | DataGridViewPaintParts.Border | DataGridViewPaintParts.ContentBackground | DataGridViewPaintParts.ErrorIcon; base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, pp); string text = formattedValue as string; //My lame attempt to indent 20 pixels?? TextRenderer.DrawText(graphics, text, cellStyle.Font, new Point(cellBounds.Location.X + 20, cellBounds.Location.Y), cellStyle.SelectionForeColor ,TextFormatFlags.EndEllipsis); }
}
If you are trying to auto-size the columns (depending on size of the cell contents) then you should look at
Column.AutoSizeModeproperty andColumn.DefaultCellStyleproperty.