LINQ and Devexpress Grid Datasource

datasourcedevexpressgridlinq

I have a DevExpress grid (DevExpress.XtraGrid.GridControl 8.2) with a datasource set at runtime like so:

private DataContext db = new DataContext("connection string");
gridControl.DataSource = from t in db.sometable
                          select new
                          {
                              Field1 = t.Name,
                              Field2 = t.Email,
                              Field3 = t.City
                          };

This means that the view has no idea what the data is going to look like at design time. I like being able to set a LINQ query as the datasource, but I'd also like to specify what the view will look like at design time.

  • Is there a way that I can tell the view that it will be using this query?
  • Would the best solution be to create a small object for holding the
    contents of what gets returned from
    this query?

Best Answer

You will have to define a class for the return type of your LINQ query if you want the DevExpress grid to automatically pick up the columns for the data source. At design time, the WinForm binding engine is using reflection or ICustomTypeDescriptor if the source implements it to automatically discover the properties, their types, etc of the data source. The DevExpress grid is using this underlying binding mechanism and automatically generating the columns for you at design time based on the property information. In your case however, you're creating an anonymous type in your LINQ query which is not known or available at design time. Therefore, DevExress Grid cannot generate the columns automatically. As @Dennis mentioned, you can manually add columns to the grid in designer. You need to make sure that 'FieldName', I believe, on the column matches the property name on your data source.

If you go with a class, you may also want to implement INotifyPropertyChanged to make the grid aware of data changes in the data source.