如何滚动到GridView中的选定行

时间:2012-05-09 09:04:29

标签: c# asp.net gridview

我有一个带有PageSize = 20(20行)的GridView,但它只显示10行而没有出现垂直滚动条。

我的问题是,当发生回发时,即使我选择了不同的行,它也会跳转到网格的顶行。我想滚动到所选行。我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

在您的网页指示中添加MaintainScrollPositionOnPostback

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" MaintainScrollPositionOnPostback ="true"%> 

另一种方法是,使用包裹GridView的DIV的scrollTop方法:

private void ScrollGrid()
{
    int intScrollTo = this.gridView.SelectedIndex * (int)this.gridView.RowStyle.Height.Value;
    string strScript = string.Empty;
    strScript += "var gridView = document.getElementById('" + this.gridView.ClientID + "');\n";
    strScript += "if (gridView != null && gridView.parentElement != null && gridView.parentElement.parentElement != null)\n";
    strScript += "  gridView.parentElement.parentElement.scrollTop = " + intScrollTo + ";\n";
    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ScrollGrid", strScript, true);
}

修改   这不会有几个原因:

1)如果gridView位于NamingContainer控件内,如Panel,因为客户端的Id不是ClientId。您需要使用UniqueId teh控件。

2)你不能相信行高来计算滚动位置。如果任何列中的文本换行到多行,或者任何行包含的内容高于样式,则行的大小将不同

3)不同的浏览器可以有不同的行为。您最好使用jQuery scrollTop()scroll()函数。要使用它们,必须在客户端使用scrollTop并设置可在服务器端读取的HiddenControl的值以重置位置。在客户端呈现行之前,您无法获得浏览器中行的高度。

答案 1 :(得分:1)

GridView的RowDataBound事件处理程序中的这段代码对我有用:

protected void dgv_usersRowDatabound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowIndex == intEditIndex)
    {
        DropDownList drpCategory = e.Row.FindControl("drpCategory") as DropDownList;
        drpCategory.Focus();
    }
 }

Gridview在每一行中都包含一个下拉列表作为EditItemTemplate。

答案 2 :(得分:0)

这对我有用,并且不需要ASP.NET AJAX,UpdatePanel或cookie,并且JavaScript比我见过的其他解决方案少得多。

<input type="hidden" runat="server" id="hdnScroll" value="0" />
<div style="height:600px; overflow-x:hidden; overflow-y:scroll">
  <asp:GridView runat="server" ID="myGridView" OnRowDataBound="myGridView_RowDataBound" OnSelectedIndexChanged="myGridView_SelectedIndexChanged">
...
</asp:GridView>
</div>

然后

protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
    //if(gr != null) gr.SelectedRow.Cells[0].Focus(); // Only works on an editable cell

    hdnScroll.Value = (myGridView.SelectedIndex * (int)myGridView.RowStyle.Height.Value).ToString();
}

最后回到.aspx,以便在回发时运行

<script type="text/javascript">
$(function() {
  document.getElementById('<%=myGridView.ClientID%>').scrollTop = $('#hdnScroll').val();
});