Reputation: 47
Have a DataGridView on which I am trying to implement sorting on header click. using linq I tried the following approach but unable to sort. Can you please guide me where It would have gone wrong
` var param = DGV.Columns[e.ColumnIndex].DataPropertyName;
var propertyInfo = typeof(EditItem).GetProperty(param);
IEnumerable<object> Items;
Items= ObjectX.BindingList();
if (so == SortOrder.Ascending)
{
DGV.DataSource = Items.OrderBy(x => propertyInfo.GetValue(x, null) as String, StringComparer.OrdinalIgnoreCase).ToList();
}
else
{
DGV.DataSource = Items.OrderByDescending(x => propertyInfo.GetValue(x, null) as String, StringComparer.OrdinalIgnoreCase).ToList();
}
grid.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = so;`
Upvotes: 1
Views: 226
Reputation: 155
Try:
if (so == SortOrder.Ascending)
{
DGV.DataSource = Items.OrderBy(x => propertyInfo.GetValue(x, null).ToString(), StringComparer.OrdinalIgnoreCase).ToList();
}
else
{
DGV.DataSource = Items.OrderByDescending(x => propertyInfo.GetValue(x, null).ToString(), StringComparer.OrdinalIgnoreCase).ToList();
}
instead. If an object is unable to be cast to the type with a safe cast as
statement, it will return null, which means it'll sort nothing.
Upvotes: 2