programmatically add column & rows to WPF Datagrid

263,037

Solution 1

To programatically add a row:

DataGrid.Items.Add(new DataItem());

To programatically add a column:

DataGridTextColumn textColumn = new DataGridTextColumn(); 
textColumn.Header = "First Name"; 
textColumn.Binding = new Binding("FirstName"); 
dataGrid.Columns.Add(textColumn); 

Check out this post on the WPF DataGrid discussion board for more information.

Solution 2

try this , it works 100 % : add columns and rows programatically : you need to create item class at first :

public class Item
        {
            public int Num { get; set; }
            public string Start { get; set; }
            public string Finich { get; set; }
        }

        private void generate_columns()
        {
            DataGridTextColumn c1 = new DataGridTextColumn();
            c1.Header = "Num";
            c1.Binding = new Binding("Num");
            c1.Width = 110;
            dataGrid1.Columns.Add(c1);
            DataGridTextColumn c2 = new DataGridTextColumn();
            c2.Header = "Start";
            c2.Width = 110;
            c2.Binding = new Binding("Start");
            dataGrid1.Columns.Add(c2);
            DataGridTextColumn c3 = new DataGridTextColumn();
            c3.Header = "Finich";
            c3.Width = 110;
            c3.Binding = new Binding("Finich");
            dataGrid1.Columns.Add(c3);

            dataGrid1.Items.Add(new Item() { Num = 1, Start = "2012, 8, 15", Finich = "2012, 9, 15" });
            dataGrid1.Items.Add(new Item() { Num = 2, Start = "2012, 12, 15", Finich = "2013, 2, 1" });
            dataGrid1.Items.Add(new Item() { Num = 3, Start = "2012, 8, 1", Finich = "2012, 11, 15" });

        }

Solution 3

I had the same problem. Adding new rows to WPF DataGrid requires a trick. DataGrid relies on property fields of an item object. ExpandoObject enables to add new properties dynamically. The code below explains how to do it:

// using System.Dynamic;

DataGrid dataGrid;

string[] labels = new string[] { "Column 0", "Column 1", "Column 2" };

foreach (string label in labels)
{
    DataGridTextColumn column = new DataGridTextColumn();
    column.Header = label;
    column.Binding = new Binding(label.Replace(' ', '_'));

    dataGrid.Columns.Add(column);
}

int[] values = new int[] { 0, 1, 2 };

dynamic row = new ExpandoObject();

for (int i = 0; i < labels.Length; i++)
    ((IDictionary<String, Object>)row)[labels[i].Replace(' ', '_')] = values[i];

dataGrid.Items.Add(row);

//edit:

Note that this is not the way how the component should be used, however, it simplifies a lot if you have only programmatically generated data (eg. in my case: a sequence of features and neural network output).

Solution 4

I found a solution that adds columns at runtime, and binds to a DataTable.

Unfortunately, with 47 columns defined this way, it doesn't bind to the data fast enough for me. Any suggestions?

xaml

<DataGrid
  Name="dataGrid"
  AutoGenerateColumns="False"
  ItemsSource="{Binding}">
</DataGrid>

xaml.cs using System.Windows.Data;

if (table != null) // table is a DataTable
{
  foreach (DataColumn col in table.Columns)
  {
    dataGrid.Columns.Add(
      new DataGridTextColumn
      {
        Header = col.ColumnName,
        Binding = new Binding(string.Format("[{0}]", col.ColumnName))
      });
  }

  dataGrid.DataContext = table;
}

Solution 5

edit: sorry, I no longer have the code mentioned below. It was a neat solution, although complex.


I posted a sample project describing how to use PropertyDescriptor and lambda delegates with dynamic ObservableCollection and DynamicObject to populate a grid with strongly-typed column definitions.

Columns can be added/removed at runtime dynamically. If your data is not a object with known type, you could create a data structure that would enable access by any number of columns and specify a PropertyDescriptor for each "column".

For example:

IList<string> ColumnNames { get; set; }
//dict.key is column name, dict.value is value
Dictionary<string, string> Rows { get; set; }

You can define columns this way:

var descriptors= new List<PropertyDescriptor>();
//retrieve column name from preprepared list or retrieve from one of the items in dictionary
foreach(var columnName in ColumnNames)
    descriptors.Add(new DynamicPropertyDescriptor<Dictionary, string>(ColumnName, x => x[columnName]))
MyItemsCollection = new DynamicDataGridSource(Rows, descriptors) 

Or even better, in case of some real objects

public class User 
{
    public string FirstName { get; set; }
    public string LastName{ get; set; }
    ...
}

You can specify columns strongly typed (related to your data model):

var propertyDescriptors = new List<PropertyDescriptor>
{
    new DynamicPropertyDescriptor<User, string>("First name", x => x.FirstName ),
    new DynamicPropertyDescriptor<User, string>("Last name", x => x.LastName ),
    ...
}

var users = retrieve some users

Users = new DynamicDataGridSource<User>(users, propertyDescriptors, PropertyChangedListeningMode.Handler);

Then you just bind to Users collections and columns are autogenerated as you speficy them. Strings passed to property descriptors are names for column headers. At runtime you can add more PropertyDescriptors to 'Users' add another column to the grid.

Share:
263,037

Related videos on Youtube

Andy
Author by

Andy

Updated on July 05, 2022

Comments

  • Andy
    Andy almost 2 years

    I'm new to WPF. I just want to know how should we add columns and rows programmatically to a DataGrid in WPF. The way we used to do it in windows forms. create table columns and rows, and bind it to DataGrid.

    I believe WPF DataGrid is bit different the one used in ASP.net and Windows form (correct me if I am wrong).

    I have No. of rows and columns which I need to draw in DataGrid so that user can edit the data in the cells.

  • JohnB
    JohnB over 13 years
    -1: because you show the painfully easy part, but not how to actually bind data to those runtime added columns. I'm sure that Andy wants to build an application that displays some sort of data, not just column names.
  • turbosaurus_rex
    turbosaurus_rex over 13 years
    It is just a matter of setting properties on the DataGridTextColumn. I updated the answer.
  • JohnB
    JohnB over 13 years
    +1: I confirmed that works, thanks. I also discovered that when you add the square brackets, i.e. Binding("[FirstName]") see my previous answer below, that it works, but it's significantly slower when binding large datasets.
  • 321X
    321X almost 13 years
    Did you find any solution for this back then??
  • smerlung
    smerlung over 9 years
    Why do you use "[{0}]" in the binding path? It doesn't work for me, but when I just use the name without square and curlies then it works?
  • C4d
    C4d almost 8 years
    As DataItem is a object, how do it has to look like?
  • zhangz
    zhangz almost 8 years
    @doblak I find this is exactly what I need. Do you still have the code of your solution?
  • doblak
    doblak almost 8 years
    @zhangz updated the answer, see this post for DynamicPropertyDescriptor idea: jopinblog.wordpress.com/2007/05/12/…
  • Denis
    Denis almost 7 years
    Is there any way to add multi column header using this code?
  • Denis
    Denis almost 7 years
    Is there any way to add multi column header using this code?
  • Mahdi Khalili
    Mahdi Khalili over 5 years
    @bartek-dzieńkowski Awesome
  • Livo
    Livo almost 3 years
    Thanks, this was the best one for my use-case!