[英]allow column based sorting on gridview
有一個網格視圖,其中有兩列需要排序。
問題是我正在獲取將數據綁定到gridview數據源的類的列表,在單擊網格列時會觸發排序表達式,但是數據源為null,所以我如何實現這一點。
標記:
<asp:GridView ID="grdDelegateList" runat="server" CssClass="gridviewBorder" AutoGenerateColumns="False" AllowSorting="true"
EmptyDataText="There are no delegates assigned for this bridge." CellPadding="2"
Style="margin-left: 0px" BackColor="White" Font-Names="Calibri" BorderWidth="1px"
Width="100%" AllowPaging="True" GridLines="Horizontal" RowHoverBackColor="#666666"
RowHoverForeColor="White" SelectedRowStyle-BackColor="#333333" SelectedRowStyle-ForeColor="White"
PageSize="20" OnPageIndexChanging="grdDelegateList_PageIndexChanging" OnRowCommand="grdDelegateList_RowCommand"
OnRowDataBound="grdDelegateList_RowDataBound"
OnRowDeleting="grdDelegateList_RowDeleting" onsorting="grdDelegateList_Sorting">
<Columns>
<asp:BoundField HeaderText="Employee ID" DataField="DelegateID" ItemStyle-HorizontalAlign="Center" SortExpression="DelegateID"
HeaderStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="Display Name" DataField="FullName" ItemStyle-HorizontalAlign="Left" SortExpression="FullName"
HeaderStyle-HorizontalAlign="Left" />
<asp:TemplateField HeaderText="Remove" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<span style="cursor: pointer">
<asp:LinkButton ID="ImgRemove" runat="server" CommandName="Delete" CommandArgument='<%# Eval("ID") %>'
Text="Remove" OnClientClick="return confirm('Are you sure you want to remove this Delegate');">
<img alt="Remove" src="Images/trash.png" style="border:0;" />
</asp:LinkButton></span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
排序表達式事件:
protected void grdDelegateList_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable table = grdDelegateList.DataSource as DataTable;//this is coming null
if (table != null)
{
DataView dataView = new DataView(table);
dataView.Sort = e.SortExpression + " " + ConvertSortDirection(e.SortDirection);
grdDelegateList.DataSource = dataView;
grdDelegateList.DataBind();
}
}
private string ConvertSortDirection(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
由於數據源為null,我是否需要再次從db獲取數據,如果是,我要獲取一個列表,那么我是否需要添加cutom邏輯首先將列表轉換為數據表,或者將其與也列出。 有什么建議么??
由於數據源是列表而不是當前方案中的數據表,因此您將獲得null。 因此,當您綁定網格時,最好使用從列表轉換后的數據表。 其余排序邏輯將不受影響。
更新:
將數據表保留在會話中。 從會話對數據表進行排序后,在排序事件中檢索並重新綁定網格。 同樣不要忘記使用更新的排序表達式來更新會話表。 參見http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.