Hi
I have below Gridview with AutoGenerateColumns = True. I want to sort on Date column
Code
C#
DataTable BookPlanningResult = sQLUtility.GeBookPlanningRecommendation(vRpl, BookCollection, StudentCollection).Tables[0];
if (BookPlanningResult != null)
{
DataColumn Remarks = new DataColumn("Remarks", typeof(string));
BookPlanningResult.Columns.Add(Remarks);
DataColumn Dates = new DataColumn("Date", typeof(DateTime));
BookPlanningResult.Columns.Add(Dates);
grdPlanning.DataSource = BookPlanningResult;
int lastColumnIndex = BookPlanningResult.Columns.Count - 1;
grdPlanning.DataBind();
}Thanks

Amit MohantyRank #112 · 20K reputationPosted May 1, 2023, 12:31 AM EDT
To sort the grid view on the Date column, you need to set the SortExpression property of the BoundField or TemplateField column that corresponds to the Date column.
Naimish MakwanaRank #324 · 7.7K reputationPosted May 1, 2023, 12:57 AM EDT
To enable sorting on the "Date" column of your GridView, you need to set the
SortExpressionproperty of the column to "Date" and also set theAllowSortingproperty of the GridView to "true". You can do this in thegrdPlanning_RowDataBoundevent handler after the GridView has been bound to the data source, like this:protected void grdPlanning_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { // Find the "Date" column and set its SortExpression property int columnIndex = -1; foreach (DataControlField column in grdPlanning.Columns) { columnIndex++; if (column.HeaderText == "Date") { column.SortExpression = "Date"; break; } } // Enable sorting on the GridView grdPlanning.AllowSorting = true; } }Thanks