Change text of the header programmatically

Hello,

how can programmtically change the text of the header of a column?
Thank you very much.

Regards

Sven Carstensen

1 Reply 1 reply marked as answer

PK Pradeep Kumar Balakrishnan Syncfusion Team February 18, 2021 07:44 AM UTC

Hi Sven, 
 
Thank you for using Syncfusion controls. 
 
We have checked your requirement “How to change the header text programmatically in SfDataGrid” define GridColumn.HeaderText value to change the header text. Refer to the following code snippet to achieve your requirement. 
 
Code Snippet: 
int index = 0; 
public MainPage() 
{ 
    InitializeComponent(); 
             
    GridTextColumn textColumn = new GridTextColumn(); 
    textColumn.MappingName = "OrderID"; 
//// Changing header text when creating column manually. 
    textColumn.HeaderText = "Order ID" + "  " + index.ToString(); 
    dataGrid.Columns.Add(textColumn); 
 
    dataGrid.AutoGeneratingColumn += dataGrid_AutoGeneratingColumn; 
    index++; 
} 
 
private void dataGrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnEventArgs e) 
{ 
//// Changing header text when columns are auto generated.  
    e.Column.HeaderText = e.Column.MappingName + "  " + index.ToString(); 
    index++; 
} 
We have also attached sample for your reference in the following link 
 
If you are looking to change the header text in run time, then define template view to column header and change the text in binding. Please to the following code snippet to achieve the same. 
 
Code Snippet:  
GridNumericColumn firstColumn = new GridNumericColumn();  
firstColumn.SetBinding(GridNumericColumn.HeaderTextProperty, new Binding("FirstColumnName", source: this.viewModel));  
firstColumn.MappingName = "OrderID";  
  
firstColumn.HeaderTemplate = new DataTemplate(() =>  
{  
    var label = new Label();  
    label.HorizontalTextAlignment = TextAlignment.Center;  
    label.HorizontalOptions = LayoutOptions.Center;  
    label.VerticalTextAlignment = TextAlignment.Center;  
    label.SetBinding(Label.TextProperty, new Binding("FirstColumnName", source: this.viewModel));  
    return label;  
});  
  
GridTextColumn secondColumn = new GridTextColumn();  
secondColumn.MappingName = "CustomerID";  
secondColumn.HeaderTemplate = new DataTemplate(() =>  
{  
    var label = new Label();  
    label.HorizontalTextAlignment = TextAlignment.Center;  
    label.HorizontalOptions = LayoutOptions.Center;  
    label.VerticalTextAlignment = TextAlignment.Center;  
    label.SetBinding(Label.TextProperty, new Binding("SecondColumnName", source: this.viewModel));  
    return label;  
});  
  
dataGrid.Columns.Add(firstColumn);  
dataGrid.Columns.Add(secondColumn);  
  
We have also attached sample for your reference in the following link.  
  
Kindly let us know if you need any further assistance on this.  
 
Regards, 
Pradeep Kumar B 


Marked as answer
Loader.
Up arrow icon