I have an asp.net web application that has a page with a GridView. The GridView is bound to an IList object. As you may know, the .net framework does not provide for sorting of such a GridView; the sorting must be handled in code.
Here's the code I was able to draft. As you can see, the issue is that the name of the field to sort by is given in the EventArgs as a string literal.
I need to get from knowing that EventArgs.SortExpression = "Subject" to telling the program to sort my list by task.Subject. If I understand correctly, this code is using the reflection libraries which are slow and should ordinarily not be used. Certainly, there is a faster way to do this. What would it be?
protected void grvAllTasks_Sorting(object sender, GridViewSortEventArgs e)
{
get_data();
IList<Task> tasks = (List<Task>) grvAllTasks.DataSource;
if (e.SortDirection == SortDirection.Ascending)
{
tasks = tasks.OrderBy( x =>
{
string propertyName = e.SortExpression;
var propertyInfo = x.GetType().GetProperty(propertyName);
var propertyValue = propertyInfo.GetValue(x, null);
return propertyValue;
}
).ToList();}
else if (e.SortDirection == SortDirection.Descending)
throw new NotImplementedException("sort descending not yet implemented");
grvAllTasks.DataSource = tasks;
grvAllTasks.DataBind();
}