A relatively simple question. I have a datagridview, which all it does is displays statistics. There is no editing/adding/deleting of rows. The datagridview is bound to a Lis
In order to be able to sort the data automatically in the DataGridView
, you need a collection that implements IBindingListView
. In the BCL, the only classes that implement this interface are DataView
and BindingSource
(but the latter only supports sorting if the underlying datasource supports it too).
So, you have several options:
DataTable
to hold the data, and bind it to the DataGridView
(it will actually bind to the DefaultView
of the DataTable
)IBindingListView
use an existing implementation, like the AdvancedList
class posted by Marc Gravell in this post. You will also need to add a constructor to build the list from the result of your query:
public AdvancedList(IEnumerable collection)
{
foreach (var item in collection)
{
Add(item);
}
}
Since the result of your query is an anonymous type, you won't be able to call the constructor directly. The easiest way to work around the issue is to take advantage of type inference, by creating a generic method that will create the list. For convenience, you can create it as an extension method:
public static AdvancedList ToAdvancedList(this IEnumerable source)
{
return new AdvancedList(source);
}
You can then use it like that:
dataGridView1.DataSource = _markets.Select(market =>
new { _cities[market.Location].Name, market.Value}).ToAdvancedList();