【问题标题】:sorting arrows in gridview not working在gridview中排序箭头不起作用
【发布时间】:2016-02-15 09:57:45
【问题描述】:

我的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>

然后在我的 rowbound 事件中我写了下面的代码

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]; 即使我向前移动光标并跳过错误,我仍然看不到向上向下的箭头。我做错了什么?

【问题讨论】:

  • 您在NameOfCity 数据字段中缺少SortExpression
  • @mhmtztmr 我不需要对 Nameofcity 进行排序

标签: c# asp.net gridview


【解决方案1】:

仅供参考,您上面的标签看起来不正确:PageSize=" 不完整。其次,您真的要添加链接按钮的文本作为图片标签吗?这似乎不正确(通常您会设置 ImageUrl)

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

然后指定自定义 css 样式

样式

th.sortasc a { 显示:块;填充:0 4px 0 15px; 背景:url(img/asc.gif)不重复; } th.sortdesc a { 显示:块;填充:0 4px 0 15px; 背景:url(img/desc.gif)不重复; }

【讨论】:

  • 我们不需要添加列吗?
  • 我发布的那篇文章有一个带有css的基本代码示例(虽然aspx与上面相同。我也会编辑以添加样式
猜你喜欢
  • 2015-12-04
  • 1970-01-01
  • 2015-09-05
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
  • 2012-09-24
相关资源
最近更新 更多