How to format the columns while auto-generating the columns in the SfDataGrid?
You can format the column by handling the AutoGenerateColumn event that is fired when the columns are auto-generated and the SfDataGrid.AutoGenerateColumns is set to true. AutoGeneratingColumnArgs provides the data for the AutoGenerateColumn event. From the AutoGeneratingColumnArgs.Column, you can get the auto-generated column to format.
this.datagrid.AutoGenerateColumns = true; this.datagrid.AutoGeneratingColumn+=datagrid_AutoGeneratingColumn; void datagrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnArgs e) { }
When the auto-generated column is GridTextColumn, you can format by setting the DisplayBinding to the column.
void datagrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnArgs e) { if (e.Column.MappingName == "EmployeeSalary") { e.Column.DisplayBinding = new Binding() { Path = new PropertyPath("EmployeeSalary"), StringFormat = "{0:C}" }; } }
When the auto-generated column is GridNumericColumn, GridDateTimeColumn, or GridPercentColumn, the column can be formatted by using the properties exposed to that particular column.
For example, in the following code example, auto-generated GridNumericColumn is formatted by using the GridNumericColumn.NumberDecimalDigits property.
void datagrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnArgs e) { if(e.Column is GridNumericColumn) (e.Column as GridNumericColumn).NumberDecimalDigits = 2; }
To apply custom format to the auto-generated column, set the DataTemplate to e.Column.CellTemplate.
void datagrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnArgs e) { if (e.Column.MappingName == "EmployeeSalary" ) { var textblock = new FrameworkElementFactory(typeof(TextBlock)); var binding = new Binding { Path = new PropertyPath("EmployeeSalary"), StringFormat = "{0:C}" }; textblock.SetBinding(TextBlock.TextProperty, binding); DataTemplate datatemplate = new DataTemplate(); datatemplate.VisualTree = textblock; e.Column.CellTemplate = datatemplate; } }
Sample Link:
WPF: http://www.syncfusion.com/downloads/support/directtrac/141004/ze/WPF1691503399