Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change DataGrid column header text

Tags:

c#

wpf

datagrid

I have a list of a specific class type Person and I want to make a DataGrid with it.

private void DataGrid_Loaded(object sender, RoutedEventArgs e) {
    List<Person> x; //Don't worry, x has data in it
    (sender as DataGrid).ItemsSource = x;
}

And the Person class:

class Person {
    string fName, lName;
}

After all this I get a table with the headers: "fName" and "lName". How can I change that to: "First Name" and "Last Name"?

like image 555
Eyal C Avatar asked Feb 12 '15 12:02

Eyal C


4 Answers

Here the Right way to do it :

First Define an ObservableCollection in the codebehind that will hold a list of persons

Second Bind that list to the DataGrid ItemSource and Bind its properties

You can change what name to display on each column by simply disabling the AutoGenerateColumns and setting their names by your self

here the full code

<DataGrid ItemsSource="{Binding ListPersons}" AutoGenerateColumns="False">
      <DataGrid.Columns >
            <DataGridTextColumn Header="First Name" Binding="{Binding FName}"></DataGridTextColumn>
            <DataGridTextColumn Header="Last Name" Binding="{Binding LName}"></DataGridTextColumn>
      </DataGrid.Columns>
  </DataGrid>

and the code behind :

public class Person
{
    public String FName { get; set; }   
    public String LName { get; set; }   

}
public partial class MainWindow : Window
{
    public ObservableCollection<Person> ListPersons { get; set; }
    public MainWindow()
    {
        ListPersons=new ObservableCollection<Person>()
        {
            new Person()
            {
                FName = "FName1",
                LName = "LName1"
            },
             new Person()
            {
                FName = "FName2",
                LName = "LName2"
            }

        };
        this.DataContext = this;

    }


}
like image 175
SamTh3D3v Avatar answered Oct 23 '22 00:10

SamTh3D3v


you can set :

 myDataGrid.Columns[0].Header="First Name";
 myDataGrid.Columns[1].Header="Last Name";
like image 21
apomene Avatar answered Oct 23 '22 00:10

apomene


if you use sql for getting data, I mean don't use entity framework you can use an Alias for your columns.

like image 2
Vecihi Baltacı Avatar answered Oct 22 '22 23:10

Vecihi Baltacı


Try this,

(sender as DataGrid).Columns[0].Header="First Name";
(sender as DataGrid).Columns[1].Header="Last Name";
like image 1
itzmebibin Avatar answered Oct 22 '22 23:10

itzmebibin