Fill WinForms DataGridView From Anonymous Linq Query
// From my form
BindingSource bs = new BindingSource()开发者_如何学运维;
private void fillStudentGrid()
{
bs.DataSource = Admin.GetStudents();
dgViewStudents.DataSource = bs;
}
// From the Admin class
public static List<Student> GetStudents()
{
DojoDBDataContext conn = new DojoDBDataContext();
var query =
(from s in conn.Students
select new Student
{
ID = s.ID,
FirstName = s.FirstName,
LastName = s.LastName,
Belt = s.Belt
}).ToList();
return query;
}
I'm trying to fill a datagridview control in Winforms, and I only want a few of the values. The code compiles, but throws a runtime error:
Explicit construction of entity type 'DojoManagement.Student' in query is not allowed.
Is there a way to get it working in this manner?
You already have an IEnumerable<Student>
instance and you cannot project entities from a query for the reasons described here)
You also don't need to create a list to bind to this data source - you can greatly simplify your method by changing it to this:
public static IEnumerable<Student> GetStudents()
{
return new DojoDBDataContext().Students;
}
There is no reason to project a new instance to only map a few of the properties, by executing the query you are returning all the values anyhow and your projection doesn't save you anything. If you really want to only return a few values from this query for the purposes of information hiding you could do this:
public static IEnumerable<Object> GetStudents()
{
DojoDBDataContext conn = new DojoDBDataContext();
return conn.Students
.Select(s => new {
ID = s.ID,
FirstName = s.FirstName,
LastName = s.LastName,
Belt = s.Belt
});
}
Edit: If you aren't using C# 4 you will have to cast the contents of the IEnumerable<T>
to Object
explicitly. Only C# 4 supports covariance for IEnumerable<T>
. So if you are using C# 3 you will have to do this:
public static IEnumerable<Object> GetStudents()
{
DojoDBDataContext conn = new DojoDBDataContext();
return conn.Students
.Select(s => new {
ID = s.ID,
FirstName = s.FirstName,
LastName = s.LastName,
Belt = s.Belt
}).Cast<Object>();
}
Once I was looking around for a solution to display results on a Gridview. The problem I had was that I forgot to set property of datagrid : "Data Source" to None on Winform.
This is simple solution for display gridview with linq (just sample code)
DataGrid dataGrid1 = new DataGrid();
var custQuery =
from cust in db.Customers
select cust;
dataGrid1.DataSource = custQuery;
Just return a list of objects of an anonymous type :
public static List<object> GetStudents()
{
DojoDBDataContext conn = new DojoDBDataContext();
var query =
(from s in conn.Students
select new
{
ID = s.ID,
FirstName = s.FirstName,
LastName = s.LastName,
Belt = s.Belt
}).Cast<object>().ToList();
return query;
}
精彩评论