I have a method for gridview sorting and paging which I am trying to make reusable for generic types but I am struggling to figure out how to make the entity context (MyContext) and table (tblReports) dynamic variables - can anyone help me out please?
protected void PopulateGridView<T>(GridView grid)
{
string columnToSortBy = (string)(ViewState["gridview_sortbycolumn"] ?? string.Empty);
SortDirection sortDirection = (SortDirection)(ViewState["gridview_sortdirection"] ?? SortDirection.Descending);
int pageIndex = (int)(ViewState["gridview_pageindex"] ?? 0);
int pageSize = grid.PageCount;
using (MyContext db = new MyContext())
{
if (columnToSortBy != string.Empty)
{
var query = db.tblReports.OrderBy(columnToSortBy + " " + sortDirection).Skip(pageIndex * pageSize);
grid.DataSource = query.ToList();
}
else
{
string defaultColumn = string.Empty;
foreach (var field in typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance))
{
defaultColumn = field.Name.Remove(field.Name.IndexOf(">")).Replace("<", string.Empty);
break;
}
var query = db.tblReports.OrderBy(defaultColumn).Skip(pageIndex * pageSize);
grid.DataSource = query.ToList();
}
grid.PageIndex = pageIndex;
grid.DataBind();
}
}
typeof(tableparameter)
instead oftypeof(T)
. Makes:PopulateGridView(grid, db.tableReports);
Look for the tblReports base class as parameter type.GetType()
to get it's type.