Change Column Header Text Dynamically

17 Feb 20222 minutes to read

You can change the column headerText dynamically through an external button.

Follow the given steps to change the header text dynamically:

Step 1:

Get the column object corresponding to the field name by using the getColumnByField method.
Then, change the header text value.

var column = grid.getColumnByField("ShipCity"); // Get column object.
column.headerText = 'Changed Text';

Step 2:

To reflect the changes in the grid header, invoke the refreshHeader method.

grid.refreshHeader();
<ejs-button id="change-text" content="Change Header Text" isPrimary="true"></ejs-button>

<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" allowGrouping="true" >    
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID"  width="150"></e-grid-column>       
        <e-grid-column field="ShipCity" headerText="Ship City" width="150"></e-grid-column>
        <e-grid-column field="ShipName" headerText="Ship Name" width="150"></e-grid-column>
    </e-grid-columns>
</ejs-grid>

<script>
    document.getElementById('change-text').addEventListener('click', () => { // changing the header text for ShipCity column.
        var grid = document.getElementById("Grid").ej2_instances[0];
        var column = grid.getColumnByField("ShipCity"); // get the JSON object of the column corresponding to the field name.
        column.headerText = "Changed Text"; // assign a new header text to the column.
        grid.refreshHeader();
    });
</script>
public IActionResult Index()
{
    ViewBag.DataSource = OrderDetails.GetAllRecords();
    return View();
}