I have a gridview which is bound to a DataTable. When I try to sort the gridview, it goes blank. How can I enable sorting this gridview?
I know this question has been asked before, but what I'm looking for is an explanation of how to do it. Perhaps with a simple example.
I have read that I need to put some code in the on_sorting and/or on_sorted events, but I don't understand what needs to go there.
Again, I want to understand the method of accomplishing this, I don't just want a giant block of code.
Ok, here's what I have now, but still not working:
<asp:GridView ID="gridResults" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="Horizontal" AllowSorting="True" AllowPaging="True"
EmptyDataText="No Tracking Information Found for the given criteria."
PageSize="15" onsorted="gridResults_Sorted" AutoGenerateColumns="False"
EnableSortingAndPagingCallbacks="True">
<RowStyle BackColor="#E3EAEB" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
And then in code behind:
//From search method
gridResults.Columns.Clear();
foreach (DataColumn col in currentResults.Columns)
{
String fieldName = col.ColumnName;
BoundField field = new BoundField();
field.DataField = fieldName;
field.SortExpression = fieldName;
field.HeaderText = fieldName;
gridResults.Columns.Add(field);
}
gridResults.DataSource = currentResults;
gridResults.DataBind();
gridResults.AllowSorting = true;
Can anyone see what I'm still missing? Results show, but no sorting or paging works.
You are able to make a GridView sortable using a DataTable. All you need to do is make sure that you have Enable Sorting = true and you provide the column name that you wish to be sorted in the SortExpression.
This is what you would need to do to allow this to be sortable:
<asp:BoundField HeaderText="Product"
DataField="ProductName" SortExpression="ProductName">
</asp:BoundField>
You always need to set the SortExpression or you are not going to be able to sort your columns
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With