DataGridTextBoxColumn.GetPreferredSize Method (Graphics, Object)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Use BaseTrue

Returns the optimum width and height of the cell in a specified row relative to the specified value.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

protected internal override Size GetPreferredSize(
	Graphics g,
	object value


Type: System.Drawing.Graphics

A Graphics object used to draw shapes on the screen.

Type: System.Object

The value to draw.

Return Value

Type: System.Drawing.Size

A Size that contains the dimensions of the cell.

The optimum width and height is calculated by measuring the string size, taking into account its font and attributes, and adding margin values.

The following example uses GetPreferredSize to return a Size.

public class Form1: Form
 protected DataGrid dataGrid1;

private void GetPreferredSize(){
   Graphics g;
   g = this.CreateGraphics();
   Size gridPreferredSize;
   MyGridColumn myTextColumn;
    // Assuming column 1 of a DataGrid control is a 
    // DataGridTextBoxColumn.
   myTextColumn = (MyGridColumn)
   string myVal;
   myVal = "A long string value";
   gridPreferredSize = myTextColumn.GetPrefSize(g, myVal);

public class MyGridColumn:DataGridTextBoxColumn{
   public Size GetPrefSize(Graphics g, string val){
      return this.GetPreferredSize(g, val);

.NET Framework
Available since 1.1
Return to top