Home > DeveloperSection > Forums > How to add Data to a WPF datagrid programmatically
jacob rasel
jacob rasel

Total Post:88

Posted on    February-03-2014 12:50 AM

 C# C# 

 1 Reply(s)
 6208  View(s)
Rate this:

I need to add Data to DataGrid programmatically in WPF which is not databind.The DataGrid has 4 columns.

Pravesh Singh

Total Post:412

Posted on    February-03-2014 1:05 AM

Hi Jacob,

In the following MainWindow.xaml I name the Grid MainGrid to access it in the code behind:

<Window x:Class="WpfExperiments.MainWindow"



        Title="MainWindow" Height="350" Width="525">

    <Grid Name="MainGrid"/>


The DataItem class is not a WPF class, but a custom class created by Yourself:

public class DataItem


    public string Column1 { get; set; }

    public string Column2 { get; set; }

    public string Column3 { get; set; }

    public string Column4 { get; set; }


To let the DataGrid display data stored in DataItem objects programmatically, You may do the following:

public partial class MainWindow : Window


    public MainWindow()



        // Your programmatically created DataGrid is attached to MainGrid here

        var dg = new DataGrid();


        // create four columns here with same names as the DataItem's properties

        for (int i = 1; i <= 4; ++i)


            var column = new DataGridTextColumn();

            column.Header = "Column" + i;

            column.Binding = new Binding("Column" + i);



        // create and add two lines of fake data to be displayed, here

        dg.Items.Add(new DataItem { Column1 = "a.1", Column2 = "a.2", Column3 = "a.3", Column4 = "a.4" });

        dg.Items.Add(new DataItem { Column1 = "b.1", Column2 = "b.2", Column3 = "b.3", Column4 = "b.4" });



I hope this helps.

Don't want to miss updates? Please click the below button!

Follow MindStick