Live Chat Icon For mobile
Live Chat Icon

How can I format columns in my DataGrid without explicitly adding DataGridColumnStyles

Platform: WinForms| Category: Datagrid

To format column output, you do not have to explicitly add DataGridColumns for each column provided you do add a DataGridTableStyle to your DataGrid prior to setting the DataSource property. When you set the DataSource property with a DataGrid that has a tablestyle with an empty columnstyle collection, the framework generates default columnstyle objects for each column in the datasource. You can then access these columnstyles directly and set properties in them such as Format, HeaderText and Width.

Download working samples here (VB.NET, C#).

Dim dataTableName As String = ''theTable''

 ’add a tablestyle to the grid so there will be custom columnstyles available
 ’    after the datasource has been set....
Dim ts As New DataGridTableStyle()
ts.MappingName = dataTableName

Me.dataGrid1.TableStyles.Add(ts)
Me.dataGrid1.DataSource = GetTheTable(dataTableName)

’now default customcolumnstyles have been created, so we can use them to set properties
Dim dgtbc As DataGridTextBoxColumn

’format the int
dgtbc = dataGrid1.TableStyles(0).GridColumnStyles(0)
If Not (dgtbc Is Nothing) Then
  dgtbc.Format = ''n0''
End If

’format the double
dgtbc = dataGrid1.TableStyles(0).GridColumnStyles(1) ’
If Not (dgtbc Is Nothing) Then
  dgtbc.Format = ''f3'' ’ 0r ''#.000''; 
End If

’format the double as currency
dgtbc = dataGrid1.TableStyles(0).GridColumnStyles(2) ’
If Not (dgtbc Is Nothing) Then
  dgtbc.Format = ''c4''
End If

’format the date
dgtbc = dataGrid1.TableStyles(0).GridColumnStyles(3) ’
If Not (dgtbc Is Nothing) Then
  dgtbc.Format = ''d'' ’ or  ''g'' or ''u'' or whatever format you want to see
  dgtbc.Width = 100 ’size it
End If

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.