WPF - Changing Column Name on Data Bound DataGrid

I used the AutoGeneratingColumn event and an Attribute to set my column names.

First create an attribute class...

    public class ColumnNameAttribute : System.Attribute
    {
        public ColumnNameAttribute(string Name) { this.Name = Name; }
        public string Name { get; set; }
    }

Then I decorate my data class members with the new attribute...

    public class Test
    {
        [ColumnName("User Name")]
        public string Name { get; set; }
        [ColumnName("User Id")]
        public string UserID { get; set; }
    }

Then I write my AutoGeneratingColumn event handler...

    void dgPrimaryGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        var desc = e.PropertyDescriptor as PropertyDescriptor;
        var att = desc.Attributes[typeof(ColumnNameAttribute)] as ColumnNameAttribute;
        if(att != null)
        {
            e.Column.Header = att.Name;
        }
    }

... and attach it to my grid and test...

        dgPrimaryGrid.AutoGeneratingColumn += dgPrimaryGrid_AutoGeneratingColumn;

        var data = new object[] 
        {
            new Test() { Name = "Joe", UserID = "1" }
        };
        dgPrimaryGrid.ItemsSource = data;

Here is what it looks like. Notice that the column names are not the property names (the default behavior).

A DataGrid with Columns Renamed

This approach is a little more work, but it's nice to have the column heading defined at the same place as the bound column. You can reorder your columns without having to go to other places to fix c the column names.


You can change it on the ItemDataBound event:

public void yourDataGrid_OnItemDataBound(object s, DataGridItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Header)
    {
        // Change the cell index to the column index you want... I just used 0
        e.Item.Cells[0].Text = "Text you want in header.";
    }
}

If the grid is already bound you should be able to do:

yourDataGrid.Columns[0].Header = "Text you want in header.";

You are probably getting an error because you are trying to change the text before it is bound.


AutoGeneratedColumns event on wpf for change column name

datagrid1.AutoGeneratedColumns += datagrid1_AutoGeneratedColumns;

void datagrid1_AutoGeneratedColumns(object sender, EventArgs e)
{
    datagrid1.Columns[0].Header = "New Column Name";
}

Tags:

C#

Wpf

Datagrid