Search code examples
c#wpfdatagridtuplescell

How to assign NON Autogenerated Columns for my DataGrid


On WPF, how should I assign to a column that I have added in code behind? Since I do not have properties associated with them I cannot Bind to them.

For example I have a list (or database) full of people and I would like to make a DataGrid with column associated with their occupation history. So I would go through the whole list and first got the list of occupation people has gone through and added as column using DataGrid.Columns.Add. And each cell I would like to display how many years they have worked in that job. So each row is not going to be filled. Some people has only worked at one place and some people has worked at 2 locations.

How should I achieve this? I have made a List<Tuple<string, int>> for each person where string Item1 would have occuption and int Item2 would have the year for that job for particular row.

I was hoping that I could modify row but unlike columns DataGrid.Rows does not exist. How can I fill in the cells?

Following image is the excel representation of what I would like to achieve. (again row represents a person column represent his/her job history)

http://clip2net.com/clip/m232864/1376442421-clip-3kb.png

In another list you might have following list etc

enter image description here


Solution

  • Use a DataTable - add the appropriate number of columns based on the overall list of occupations found, and then create a row with each person's information. If you bind the DataGrid to the DataTable in your ViewModel, it will autogenerate the appropriate columns for you.

    This answer shows how: https://stackoverflow.com/a/9306756/1329939