0

GridView で lbl フィールド テキストを動的に設定するための並べ替えを有効にする方法。以下は、動的ラベル フィールドの値を設定している GridView および .cs コードのコードです。問題は、他のテンプレートと同様に、この特定の asp:template に並べ替え式を適用できないことです。

<asp:GridView ID="gvAlertsStatus" runat="server" AllowSorting="true"
    OnSorting="gvAlertsStatus_Sorting" AutoGenerateColumns="false"
    OnRowDataBound="gvAlertsStatus_RowDataBound">
    <Columns>
        <asp:TemplateField HeaderText="Owner" SortExpression="UsrName"
            ItemStyle-Width="120px">
            <ItemTemplate><%#Eval("UsrName") %></ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Last Result" SortExpression="lblLastResult"
            ItemStyle-Width="40px" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblLastResult" Font-Bold="true">
                </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Active" SortExpression="Active"
            ItemStyle-Width="60px" >
            <ItemTemplate>
                <asp:Label runat="server" ID="lblActive"
                    Text='<%#Eval("Active") %>' >
                </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

.aspx.cs コード

public void gvAlertsStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowIndex >= 0)
    {
         Label lblLastResult = (Label)e.Row.FindControl("lblLastResult");
        // Get the dates
        DateTime dtSuccess = (eScan.Lib.Shared.Utils.IsDate(lblSuccess.Text)) ?
            DateTime.Parse(lblSuccess.Text) : DateTime.MinValue;
        DateTime dtFailure = (eScan.Lib.Shared.Utils.IsDate(lblFailure.Text)) ?
            DateTime.Parse(lblFailure.Text) : DateTime.MinValue;
        DateTime dtDelay = (eScan.Lib.Shared.Utils.IsDate(lblDelay.Text)) ?
            DateTime.Parse(lblDelay.Text) : DateTime.MinValue;
        DateTime dtLastRun = (dtSuccess > dtFailure) ? dtSuccess : dtFailure;

        // Set up the Last Result label
        lblLastResult.Text = (dtSuccess > dtFailure) ? "Success" : "Fail";            
    }
}

protected void gvAlertsStatus_Sorting(object sender, GridViewSortEventArgs e)
{
    // Set up the sort direction
    SortDirection sd = SortDirection.Ascending;

    // If the same column is clicked, then alternate sort direction
    if (e.SortExpression.Equals(ViewState["SortExp"]))
    {
        sd = ((SortDirection)ViewState["SortDir"] == SortDirection.Descending) ?
            SortDirection.Ascending : SortDirection.Descending;
    }

    // Save the states
    ViewState["SortExp"] = e.SortExpression;
    ViewState["SortDir"] = sd;

    // Sort the view and rebind that 
    DataView dv = (DataView)gvAlertsStatus.DataSource;
    dv.Sort = e.SortExpression + " " +
        ((sd == SortDirection.Descending) ? "DESC" : "ASC");

    gvAlertsStatus.DataSource = dv;
    gvAlertsStatus.DataBind();
}
4

1 に答える 1