I'm trying to make DataGridView
form which takes generic DataSource
and displays data.
I can't get data bindings to work:
An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.dll
Additional information: Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery, DbRawSqlQuery) is not supported. Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data. For WPF bind to DbSet.Local. For WinForms bind to DbSet.Local.ToBindingList(). For ASP.NET WebForms you can bind to the result of calling ToList() on the query or use Model Binding, for more information see http://go.microsoft.com/fwlink/?LinkId=389592.
I tried passing DataTable
, DataSet
and List
- but no luck... my problem is I want to use repository pattern and make a generic repository class which can work with different tables in my database.
This is my first attempt at writing the repository pattern code, and working with generic types.
public DataGridForm(IEnumerable<???> source) // TEntity or T can't be recognized by VisualStudio as a type!
{
InitializeComponent();
// TODO: Complete member initialization
this.bindingSource.DataSource = source;
}
I'm having hard time with making this simple. Please any guidelines on how to achieve this?
I call this method:
public IEnumerable<TEntity> GetAll()
{
return Context.Set<TEntity>().ToList();
}
I know this is a loaded question but I need help in one way or another
~ ChenChi
UPDATE: the accepted answer works without a problem, real problem was that my AutoGenerateColumns property was by default set to false!
dataGridView.AutoGenerateColumns = true;
Setting it to true via code-behind made everything work... I was looking for this property in property windows and I couldn't find it?! Maybe some kind of Visual Studio bug I don't know...
DataSource
property of BindingSource
accepts object
. So it's enough to pass data as object
to the constructor of your form:
public DataGridForm(object source)
{
InitializeComponent();
// TODO: Complete member initialization
this.bindingSource.DataSource = source;
}
For run-time data-binding you don't need the type. But for any reason if you want to pass IEnumerable<T>
to the form, the form should be DataGridForm<T>
which has its side effects in designer.