2016-02-15 96 views
0

我在rowbound事件定义如下在GridView中排序箭头不工作

<asp:GridView ID="MyDataGridView" runat="server" CellPadding="4" GridLines="None" 
    AutoGenerateColumns="False" EmptyDataText="No records found" AllowSorting="True" 
    AllowPaging="True" PageSize="2" 
    OnPageIndexChanging="MyDataGridView_OnPageIndexChanging" OnSorting="MyDataGridView_OnSorting" OnRowDataBound="MyDataGridView_OnRowDataBound"> 
    <Columns> 
      <asp:BoundField DataField="CreatedDate" HeaderText="CreatedDate" SortExpression="CreatedDate" /> 
      <asp:BoundField DataField="NameOfCity" HeaderText="Cityname" /> 

    </Columns> 
</asp:GridView> 

然后我写了下面的代码的GridView

protected void MyDataGridView_OnRowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     string imgAsc = @" <img src='../Images/asc.gif' border='0' title='Ascending' />"; 
     string imgDes = @" <img src='../Images/desc.gif' border='0' title='Descendng' />"; 
     if (e.Row.RowType == DataControlRowType.Header) 
     { 
      foreach (TableCell cell in e.Row.Cells) 
      { 
       LinkButton lnkbtn = (LinkButton)cell.Controls[0]; 
       if (lnkbtn.Text == MyDataGridView.SortExpression) 
       { 
        if (DataGridView.SortDirection == SortDirection.Ascending) 
        { 
         lnkbtn.Text += imgAsc; 
        } 
        else 
         lnkbtn.Text += imgDes; 
       } 
      } 
     } 
    } 

但是,当运行代码,然后我得到错误“指定的参数超出有效值的范围参数名称:索引“

当我调试我发现我得到这个错误在foreach循环里面,当它进入第二次。 它就行LinkButton lnkbtn = (LinkButton)cell.Controls[0]; 即使我向前移动光标并跳过错误,我仍然无法看到向下的箭头。我究竟做错了什么?

+0

你在'NameOfCity'数据字段 – mhmtztmr

+0

@mhmtztmr我不需要分拣Nameofcity – Happy

回答

0

FYI您的标签上面看起来不正确:?每页=”不完整其次,你真的想要一个链接按钮的文本添加为​​图像标签这个看起来不正确(通常你设置一个的ImageUrl)

有不同的方法。按照http://blogs.msdn.com/b/scothu/archive/2010/08/28/gridview-with-sort-arrows-and-showing-header-when-empty.aspx 您可以定义一些模板

 
<SortedAscendingHeaderStyle /> 
<SortedDescendingHeaderStyle /> 
<SortedAscendingCellStyle /> 
<SortedDescendingCellStyle /> 

,进而指定自定义CSS样式

 
    <asp:GridView ID="GridView1" runat="server" AllowSorting="True" DataSourceID="EntityDataSource1" PageSize="5"> 
     <SortedAscendingHeaderStyle CssClass="sortasc" /> 
     <SortedDescendingHeaderStyle CssClass="sortdesc" /> 
    </asp:GridView> 

样式

 
th.sortasc a 
{ 
    display:block; padding:0 4px 0 15px; 
    background:url(img/asc.gif) no-repeat; 
} 

th.sortdesc a 
{ 
    display:block; padding:0 4px 0 15px; 
    background:url(img/desc.gif) no-repeat; 
} 

+0

不要我们需要添加列misssing'SortExpression'? – Happy

+0

我也试过你的方法,但没有任何显示 – Happy

+0

我发布的这篇文章有一个基本的css代码示例(aspx虽然与上面相同,但我也会编辑以添加样式 –