Search code examples
c#wpfdatagrid

How to correctly add a row to a datagrid in WPF?


I have this DataGrid:

enter image description here

Code:

        <DataGrid Name="DatabaseView1" Grid.Row="1">
            <DataGrid.Columns>
                <DataGridTextColumn Header="First name" Binding="{Binding Path=FirstName}"/>
                <DataGridTextColumn Header="Last name" Binding="{Binding Path=LastName}"/>
                <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}"/>
            </DataGrid.Columns>
        </DataGrid>

This datagrid contains several entries one after the other. I collect the entries in a list:

        public static List<Entry> Entries = new List<Entry>();
        public class Entry
        {
            public string FirstName { get; set; }
            public string Lastname { get; set; }
            public int Age { get; set; }
        }

I add a new entry like this:

Entries.Add(new Entry {FirstName = "Christiano", LastName = "Ronaldo", Age = "35"});

I add the entries like this to the DataGrid:

DatabaseView1.ItemsSource = Entries;

This is my result:

enter image description here

You see that two entries are created. Does anyone know why this happens?

Thank you in advance.


Solution

  • Double columns are being generated because you have not told DataGrid to stop auto generating columns for assigned ItemSource. So, to disable AutoGenerateColumns Just set the AutoGenerateColumns = False in xaml DataGrid.

    <DataGrid Name="DatabaseView1" Grid.Row="1" AutoGenerateColumns = "False">