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.
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
xaml.cs using System.Windows.Data;
If you already have the databinding in place John Myczek answer is complete.
If not you have at least 2 options I know of if you want to specify the source of your data. (However I am not sure whether or not this is in line with most guidelines, like MVVM)
option 1: like JohnB said. But I think you should use your own defined collection instead of a weakly typed DataTable (no offense, but you can't tell from the code what each column represents)
xaml.cs
in xaml.cs
If your type has a property FirstName defined, you can then do what John Myczek pointed out.
This obviously doesn't work if you don't know properties you will need to show in your dataGrid, but if that is the case you will have more problems to deal with, and I believe that's out of scope here.