2

How do I bind to a WPF grid with an unknown number of columns?

I have a class that can return the number of columns and column names, etc. as well as the items that will get bound to each row. Basically, I want to do what the DataTable can do without using the datatable. There must be an interface I need to implement or something like that.

3 Answers 3

1

If your object(DataContext) implements IEnumerable the datagrid will be able to suck-in the object and display the records. Just set AutoGenerateColumns to true and it will generate the columns for you based on the object you passed.

4
  • Thanks for the reply. I don't think this will solve the problem because I don't know the column names until I query the database. Also, if the collection is empty then I won't get any columns. In my case the columns will be days which the user could name Day1, Day2 etc or mon, tue. The rows will be timeslots 8-9am, 9-10am etc.
    – MikeKulls
    Apr 11, 2011 at 3:48
  • Lets say you get 10 columns for a perticular user.. When you get the results back (supposed in a datatable) you can run a loop based on the number of columns returned.. Why do you want to know how many columns returned??
    – sajoshi
    Apr 14, 2011 at 6:47
  • That's what I want to do except without using the datatable. I am using linq to entities to get data back in a collection but I don't have the standard model where one object equals a row. In my case, I have a collection that represents row, a collection that represents columns and a collection that represents cells. I could stick all of my data into a datatable but that seems hacky to me. Linq is meant to be a replacement for datatables and should not need to rely on it :-)
    – MikeKulls
    May 17, 2011 at 3:25
  • @MikeKulls - I am not sure why you have 3 different collections. Can you represent the collection in terms a table and how they relate to each other.. If you can - then you can use joins to get the actual display row..
    – sajoshi
    May 18, 2011 at 2:14
1

I ended up solving this problem by using the SyncFusion grid control. I found that the built-in grid, as well as pretty much every grid on the market, is very orientated towards one row being an object returned from the database.

If you deviate from this model then most grids becomes useless or at least very difficult to work with. In my case, each row from the database represented a single cell. The key problem I had with all grid was getting a WPF template to work with the unbound data. The SyncFusion grid was the only one I could find that would work with these two features together (ubound data and data templates).

I also found that the flexgrid will solve this problem although it was a little difficult to work with in this regard.

-1

Updated


The best solution is to use Anonymous Types. It works perfectly, see the following proof of concept:

<Window x:Class="AnonymousTypes.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="OnWindowLoaded">
    <Grid>
        <DataGrid Name="MyDataGrid" ItemsSource="{Binding}" AutoGeneratedColumns="OnMyDataGridAutoGeneratedColumns">

        </DataGrid>
    </Grid>
</Window>

The code-behind:

using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;

namespace AnonymousTypes
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public class Employee
        {
            public int Id { get; set; }
            public string Code { get; set; }
            public string Name { get; set; }
            public int Job { get; set; }
            public string Address { get; set; }
        }

        private ObservableCollection<Employee> _empCollection;

        private void OnWindowLoaded(object sender, RoutedEventArgs e)
        {
            // Generate test data
            _empCollection =
                new ObservableCollection<Employee>
                    {
                        new Employee {Id = 234, Code = "E041", Name = "Employee1", Job = 1, Address = "..."},
                        new Employee {Id = 245, Code = "E701", Name = "Employee2", Job = 3, Address = "..."},
                        new Employee {Id = 728, Code = "E001", Name = "Employee3", Job = 9, Address = "..."},
                        new Employee {Id = 663, Code = "E051", Name = "Employee4", Job = 7, Address = "..."},
                    };
            // Notice that here you can chose the column you want,
            // and it can be variable with each query depending on your needs
            // Just add the columns you need to the anonymous type
            DataContext =
                (from i in _empCollection
                 select new {TheCode =  i.Code, TheName = i.Name, TheAddress = i.Address }).ToList();
        }

        private void OnMyDataGridAutoGeneratedColumns(object sender, EventArgs e)
        {
            // Now you can change the column names as you need
            MyDataGrid.Columns[0].Header = "Header 1 [Code]";
            MyDataGrid.Columns[1].Header = "Header 2 [Name]";
            MyDataGrid.Columns[2].Header = "Header 3 [Address]";
        }
    }
}

You can change the columns headers after the data binding finishes using the AutoGeneratedColumns event.

6
  • Thanks for the reply. The problem with that is the columns are still reqired to be compiled into the application. I don't know the column names until I query the database.
    – MikeKulls
    Apr 11, 2011 at 3:44
  • No, problem, the important part in my solution is the last three lines, the rest is just to show my proof of concept. In the last three lines notice that I selected just three out five properties dynamically from the Employee class, you can do the same, of-course you have some sort of result set that contains the result of your query to the database, hence, you can do the same as I did, selecting the columns you want from the result set dynamically with respect to some conditions. Apr 11, 2011 at 3:56
  • Hi Mohammed, that won't work for me because I don't know the column names ahead of time. In the code you've provided the compiler will create a class with properties of Code, Name and Address. This is not dynamic, it is something that is hard coded into your application.
    – MikeKulls
    Apr 11, 2011 at 4:02
  • What I mean by dynamic is the selection of the columns themselves. regarding the column headers, there is no way to set them dynamically for data bound DataGrids, you have to change the headers after the DataBiniding finishes, see the updated solution. Apr 11, 2011 at 4:34
  • Thanks again Mohammed. The problem is the user can enter 10 or 20 or 50 columns into the database. In your example you are still hard coded to 3 columns which are all hard coded to certain properties in your class. The header can be changed but that doesn't change where the data came from. Imaging I am starting with a class like this:
    – MikeKulls
    Apr 11, 2011 at 4:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.