programmatically add column & rows to WPF Datagrid

Andy picture Andy · Apr 1, 2009 · Viewed 244.1k times · Source

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.

Answer

John Myczek picture John Myczek · Apr 1, 2009

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.