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.
try this , it works 100 % : add columns and rows programatically : you need to create item class at first :
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://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).
To programatically add a row:
To programatically add a column:
Check out this post on the WPF DataGrid discussion board for more information.
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)
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.
To Bind the DataTable into the DataGridTextColumn in CodeBehind xaml
xaml.cs
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:
You can define columns this way:
Or even better, in case of some real objects
You can specify columns strongly typed (related to your data model):
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.