【问题标题】:Why is SortExpression of GridView getting empty on RowDataBound - C#为什么 GridView 的 SortExpression 在 RowDataBound 上变空 - C#
【发布时间】:2020-02-08 19:22:22
【问题描述】:

我想在我的排序网格视图的标题上显示一个向上/向下箭头。我已经在下面附加的代码中实现了它,但是在行数据绑定事件中,sortexpression 为空。因此,我无法设置排序方向的图像。

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CssClass="gridview_alter"  GridLines="Both"  
Caption="Submissions today"  CaptionAlign="Top"          
AllowSorting="true"
AllowPaging="true"  PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging" 
OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" 
OnSorting="GridView1_Sorting">

<Columns>
<asp:BoundField DataField="student_name" HeaderText="student_name" 
ReadOnly="True"  SortExpression="student_name">  </asp:BoundField>                             
<asp:BoundField DataField="Role" HeaderText="Role" 
ReadOnly="True"  SortExpression="Role">  </asp:BoundField>                  
</Columns> 

</asp:GridView>

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  string imgAsc = @" <img src='~/images/up.png' border='1' title='Ascending' 'width='50' height='50' />";
  string imgDes = @" <img src='~/images/dwn.png' border='1' title='Descendng' 'width='50' height='50' />";
 if (e.Row.RowType == DataControlRowType.Header)
 {
        foreach (TableCell td in e.Row.Cells)
        {
         LinkButton lnkbtn = (LinkButton)td.Controls[0];

        if (lnkbtn.Text == GridView1.SortExpression)//sortexpression is grtting empty here
            {
                if (GridView1.SortDirection == SortDirection.Ascending)
                {
                    lnkbtn.Text += imgAsc;
                }
                else
                    lnkbtn.Text += imgDes;
            }
        }
    }

【问题讨论】:

  • 我投了反对票,因为the code is poorly formatted,这让人难以阅读。
  • 请立即查看
  • 我很确定你没有改变任何东西。如果您想编辑您的问题,请点击“编辑”。
  • 请立即查看

标签: c# asp.net gridview sortexpression


【解决方案1】:

检查 sortexpression(以及任何基于排序的工作)的最佳位置是 Gridview 的 OnSorting 事件。

因此,在此 OnSorting 事件中,您可以获得 Header Row 并应用 ASC / DESC 图像。

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
  {
    // Get the header row.
    GridViewRow headerRow = GridView1.HeaderRow;
    if(headerRow != null)
     {
        foreach (TableCell td in headerRow.Cells)
         {
            LinkButton lnkbtn = (LinkButton)td.Controls[0];

             if (lnkbtn.Text == e.SortExpression)
               {
                  if (GridView1.SortDirection == SortDirection.Ascending)
                  {
                      lnkbtn.Text += imgAsc;
                  }
                  else
                    lnkbtn.Text += imgDes;
               }
         }        
     }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多