views:

1092

answers:

2

Hello fellows,

I have a WinForms application with DataGridView control. My control has five columns (say "Name", "Address", "Phone" etc)

I am not happy with default column width. I want to have more control over column appearance. What I want is to be able to do one of the following:

  • Set width of each column in percent
  • Set width of each column in pixels
  • Use some other best-practive method (make width to fit text etc)

Please suggest - which property to use and how.

+1  A: 

You can use the DataGridViewColumn.Width property to do it:

DataGridViewColumn column = dataGridView.Columns[0];
column.ItemStyle.Width = 60;

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.width.aspx

Bhaskar
Thanks! I just realized why it was not working for me. MSDN saysIf the specified value when setting this property is less than the value of the MinimumWidth property, the MinimumWidth property value is used instead.
Captain Comic
Yes, width is not available directly to the Grid control, so you use ItemStyle.With to set its property.
Bhaskar
+1  A: 

Regarding your final bullet

make width fit the text

You can experiment with the .AutoSizeMode of your DataGridViewColumn, setting it to one of these values:

None
AllCells
AllCellsExceptHeader
DisplayedCells
DisplayedCellsExceptHeader
ColumnHeader
Fill

More info on the MSDN page

hawbsl