---
title: "How to add Data to a WPF datagrid programmatically"  
description: "How to add Data to a WPF datagrid programmatically"  
author: "Anonymous User"  
published: 2014-02-03  
updated: 2014-02-03  
canonical: https://www.mindstick.com/forum/1947/how-to-add-data-to-a-wpf-datagrid-programmatically  
category: "c#"  
tags: ["c#"]  
reading_time: 2 minutes  

---

# How to add Data to a WPF datagrid programmatically

I need to [add Data](https://www.mindstick.com/forum/34130/how-to-add-data-into-the-post-method-of-a-form-in-extjs) to DataGrid programmatically in [WPF](https://www.mindstick.com/forum/304/wpf) which is not databind.The DataGrid has 4 columns.

## Replies

### Reply by Pravesh Singh

Hi Jacob,\

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

```
<Window x:Class="WpfExperiments.MainWindow"       
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"       
Title="MainWindow" Height="350"
Width="525">    <Grid
Name="MainGrid"/></Window>
```

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

```
public class DataItem{    public stringColumn1 { get; set; }    public stringColumn2 { get; set; }    public stringColumn3 { get; set; }   
    public stringColumn4 { get; set; }}
```

To let the DataGrid display [data](https://www.mindstick.com/articles/13050/salesforce-aiming-to-dominate-predictive-analytics-with-data-science) stored in DataItem objects programmatically, You may do the following:

```
public partial class MainWindow : Window{    public MainWindow()    {        InitializeComponent();        // Your programmatically created DataGrid is attached to MainGrid here        var dg = new DataGrid();        this.MainGrid.Children.Add(dg);        // 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);            dg.Columns.Add(column);        }        // 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.


---

Original Source: https://www.mindstick.com/forum/1947/how-to-add-data-to-a-wpf-datagrid-programmatically

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
