I have a DataGridView assigned to this query.
dgvArtists.DataSource = (from a in context.Artists
orderby a.BirthName
select new
{
a.ArtistId,
a.BirthName,
a.DateOfBirth,
a.Songs.Count
}).ToList();
When I click on the header, I want it to sort, but I keep getting this error.
'DataGridView control must be bound to an IBindingList object to be sorted.'
This is the header method that is being activated where I am getting the error:
private void dgvArtists_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (dgvArtists.Columns[e.ColumnIndex].SortMode != DataGridViewColumnSortMode.NotSortable)
{
if (e.ColumnIndex == newSortColumn)
{
if (newColumnDirection == ListSortDirection.Ascending)
newColumnDirection = ListSortDirection.Descending;
else
newColumnDirection = ListSortDirection.Ascending;
}
newSortColumn = e.ColumnIndex;
switch (newColumnDirection)
{
case ListSortDirection.Ascending:
dgvArtists.Sort(dgvArtists.Columns[newSortColumn], ListSortDirection.Ascending);
break;
case ListSortDirection.Descending:
dgvArtists.Sort(dgvArtists.Columns[newSortColumn], ListSortDirection.Descending);
break;
}
}
}
What I have tried:
I have read:
Implementing a Sortable BindingList Very, Very Quickly[
^] but I do not know what do put in for:
MySortableBindingList<SaleDetails>sortableSaleDetails =
new MySortableBindingList<SaleDetail>();
I've created a class that only contains the properties I want it to return like it says in:
Cannot convert from System.Linq.IQueryable<AnonymousType> to System.Collections.Generic.IEnumerable<myobject>[
^]
class ArtistList
{
public int ArtistId { get; set; }
public string Last_Name { get; set; }
public int Age { get; set; }
public int Song_Count { get; set; }
}
List<ArtistList> xList = new List<ArtistList>();
xList = (from a in context.Artists
orderby a.BirthName
select new ArtistList
{
ArtistId = a.ArtistId,
Last_Name = a.BirthName.Split(space).Last(),
Age = a.DateOfDeath.HasValue ?
(Convert.ToDateTime(a.DateOfDeath).Year - a.DateOfBirth.Year) :
(DateTime.Today.Year - a.DateOfBirth.Year),
Song_Count = a.Songs.Count
}).ToList();
dgvArtists.DataSource = xList;