【问题标题】:How to navigate (up or down) in ASP.NET gridview using arrow keys?如何使用箭头键在 ASP.NET gridview 中导航(向上或向下)?
【发布时间】:2014-10-27 06:14:03
【问题描述】:

如何在 ASP.NET gridview 中使用箭头键导航(向上或向下)同时突出显示当前行?

我可以使用 javascript 代码和 C# 代码使用向上和向下箭头键在行中移动。我还实现了一个开始请求和结束请求 JS 代码,用于在回发时保持滚动位置。

但是,我的问题是,滚动条不会向上或向下移动以自动显示突出显示的行。假设有 100 行,我选择第 15 行,但是网格高度好像只能显示 10 行,除非我们手动移动滚动条,否则它不会自动移动以显示通过箭头键选择的行。如何通过移动滚动条确保高亮行的同步或可见性?

我的 gridview 没有复选框。

请帮助我。这是我的代码:

<asp:GridView ID="gvCycles" runat="server" AutoGenerateColumns="False" 
    CssClass="grid"
    AllowSorting="True"
    ShowHeader="False"
    ShowFooter="True"
    OnSelectedIndexChanged="gvDeductionList_SelectedIndexChanged" 
    OnRowDataBound="gvDeductionList_RowDataBound" DataKeyNames="CycleID" onselectedindexchanging="gvCycles_SelectedIndexChanging"
    >
    <Columns>               
        <asp:BoundField DataField="CycleID" HeaderText="CycleID"
            HtmlEncode="False"                    
            SortExpression="CycleID">
            <ItemStyle CssClass="GridViewHiddenColumn" />    
        </asp:BoundField> 

我在回发时保持滚动位置的方法是:

<script language="javascript" type="text/javascript">
    // This Script is used to maintain Grid Scroll on Partial Postback
    var scrollTop;
    //Register Begin Request and End Request 
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    //Get The Div Scroll Position
    function BeginRequestHandler(sender, args) {
        var m = document.getElementById('divGrid');
        scrollTop = m.scrollTop;
    }
    //Set The Div Scroll Position
    function EndRequestHandler(sender, args) {
        var m = document.getElementById('divGrid');
        m.scrollTop = scrollTop;
    } 
</script>

另外,我在 keydown 和 keyup 中有这个

 if (e.keyCode == '38') {
                document.getElementById('<%= controlCapture.ClientID %>').value = false;
                document.getElementById('<%= shiftCapture.ClientID %>').value = false;
                // up arrow
                __doPostBack(pageId, "up");
            }
else if (e.keyCode == '40') {
                document.getElementById('<%= controlCapture.ClientID %>').value = false;
                document.getElementById('<%= shiftCapture.ClientID %>').value = false;
                              // down arrow
                __doPostBack(pageId, "down");

问题:我不知道在哪里使用您在代码项目中提到的代码,这样,当我按下向下或向上箭头键时,它应该会自动移动滚动条。我没有分页。

页面加载代码

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) //on initial load, default dates to current fbt year
        {
            dpDateFrom.DateValue = currentBT;
            dpDateTo.DateValue = currentBTEnd;

            Searchclick();
        }
            //cursor keys
        else if (Request.Form["__EVENTARGUMENT"] == "up" || Request.Form["__EVENTARGUMENT"] == "down")
        {
            string eventArgument = Request.Form["__EVENTARGUMENT"];
            int intPayCycleId = 0;

            if (gvCycles.SelectedIndex >= 0 && gvCycles.SelectedIndex < gvCycles.Rows.Count)
            {
                if (eventArgument == "down")
                {
                    if (gvCycles.SelectedIndex < gvCycles.Rows.Count-1)
                    {
                        gvCycles.SelectedIndex += 1;

                    }
                }
                else if (eventArgument == "up")
                {
                    if (gvCycles.SelectedIndex > 0)
                    {
                        gvCycles.SelectedIndex -= 1;
                    }
                }

                hdnSelectedRow.Value = gvCycles.SelectedValue.ToString() + ","; //assign hidden value with selected row
                SetRowsStyle(gvCycles);

                if (int.TryParse(gvCycles.SelectedRow.Cells[0].Text, out intCycleId))
                {
                    ShowDeductions(intCycleId, false);
                }
            }
        }
    }

【问题讨论】:

  • 有什么想法或想法吗?有人可以帮我实现这个目标的javascript代码吗?我无法在整个互联网上获得任何资源。 23 次观看,还没有答案!
  • 先分享你的代码。没有看到您的代码的人如何提供帮助?
  • Sam,再次感谢您,我不知道如何将它用于我的 gridview。看,我没有table,但是gridview。如果您阅读他提到的最后一行,作者只写了网格的左右箭头键。我只希望它在我传递我拥有的网格视图的名称时不起作用。我做得对吗?
  • 好的,给我一些时间。我正在做一些工作,很快就会看看。干杯!
  • 是的,我来自维多利亚。你从哪来?能否也分享一下Page_Load和keyup和keydown的JS代码?

标签: javascript c# jquery asp.net gridview


【解决方案1】:

看看这个SO线程

还有,here's 一个很棒的示例代码

更新

我刚刚查看了代码here。如果您使用 DIV 包装 GridView,则自动滚动可以正常工作,如下所示。 (我使用的代码与this link 中给出的代码相同,只是添加了带有CSS 样式的DIV。还通过将后面代码中的for 循环更改为n &lt; 100 来增加网格中显示的记录数)

<div class="scrollable">
        <asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" OnRowCreated="gridView_RowCreated"
            TabIndex="0" GridLines="Horizontal">
            <Columns>
                <asp:BoundField HeaderText="S#" DataField="sno">
                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
                </asp:BoundField>
                <asp:BoundField HeaderText="Random No" DataField="rndno">
                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="150px" />
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="150px" />
                </asp:BoundField>
                <asp:BoundField HeaderText="Date" DataField="date">
                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
                </asp:BoundField>
                <asp:BoundField HeaderText="Time" DataField="time">
                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
                </asp:BoundField>
            </Columns>
            <RowStyle BackColor="#FFE0C0" />
            <HeaderStyle BackColor="#FF8000" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="#FFC080" />
        </asp:GridView>
      </div>

还有,这是 CSS

<style type="text/css">
    .scrollable {
        height: 460px;
        width: 100%;
        overflow: auto;
        border: 0;
    }
    </style>

更新 2

  1. 注释您的 JavaScript 代码(它有一个 __doPostBack,它将执行回发并导致您的滚动条行为不端)

  2. 评论你的Page_Load事件的else if部分,因为你评论了你的JS代码,我们不会使用它

  3. 现在将以下代码添加到您的页面

JavaScript

<script type="text/javascript">
    var SelectedRow = null;
    var SelectedRowIndex = null;
    var UpperBound = null;
    var LowerBound = null;

    window.onload = function()
    {
        UpperBound = parseInt('<%= this.gvCycles.Rows.Count %>') - 1;
        LowerBound = 0;
        SelectedRowIndex = -1;        
    }

    function SelectRow(CurrentRow, RowIndex)
    {        
        if(SelectedRow == CurrentRow || RowIndex > UpperBound || RowIndex < LowerBound) return;

        if(SelectedRow != null)
        {
            SelectedRow.style.backgroundColor = SelectedRow.originalBackgroundColor;
            SelectedRow.style.color = SelectedRow.originalForeColor;
        }

        if(CurrentRow != null)
        {
            CurrentRow.originalBackgroundColor = CurrentRow.style.backgroundColor;
            CurrentRow.originalForeColor = CurrentRow.style.color;
            CurrentRow.style.backgroundColor = '#DCFC5C';
            CurrentRow.style.color = 'Black';
        } 

        SelectedRow = CurrentRow;
        SelectedRowIndex = RowIndex;
        setTimeout("SelectedRow.focus();",0); 
    }

    function SelectSibling(e)
    { 
        var e = e ? e : window.event;
        var KeyCode = e.which ? e.which : e.keyCode;

        if(KeyCode == 40)
            SelectRow(SelectedRow.nextSibling, SelectedRowIndex + 1);
        else if(KeyCode == 38)
            SelectRow(SelectedRow.previousSibling, SelectedRowIndex - 1);

        return false;
    }
    </script>

代码背后

protected void gvCycles_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
        {
            e.Row.TabIndex = -1;
            e.Row.Attributes["onclick"] = string.Format("javascript:SelectRow(this, {0});", e.Row.RowIndex);
            e.Row.Attributes["onkeydown"] = "javascript:return SelectSibling(event);";
            e.Row.Attributes["onselectstart"] = "javascript:return false;";
        }
    }

希望这会有所帮助。

【讨论】:

  • 我在我的 div 中注释了属性,并通过粘贴代码使用了上述可滚动的样式类。然后我还评论了包含所有 keyup 和 down 事件的 JS 代码,现在我看到两个滚动条 :D 大声笑我所有的现有功能都坏了,因为在 row 中没有选择箭头 keydown 事件
  • 所以你没有按照我的要求去做。无需评论您的 DIV。把它留在那里。并且,不要使用 Style 添加新的 DIV(我建议您认为您没有 div)。然后按照我更新的答案(更新 2)中的步骤进行操作
  • Sam,谢谢,它部分有效,但并非总是如此。它仅在我向下滚动并选择最后一行然后按向上箭头键时才有效。而且,让我告诉你,当我使用开始请求启用我的 JS 代码以保持滚动位置时,问题再次发生,它不会自动滚动。所以恐怕这不是解决办法。或者可以做任何调整?
  • Sam,现在我再次尝试了您的代码或建议,它根本不起作用,甚至现有功能也不起作用
  • 好的,您如何投票并接受这个答案,因为它解决了您的初始问题(使用箭头键上下移动),然后使用您当前的逻辑创建一个新问题,因此我们将专注于?
猜你喜欢
  • 2011-01-02
  • 2012-10-06
  • 2021-11-07
  • 2018-11-15
  • 1970-01-01
  • 2015-11-24
  • 2022-11-17
  • 2010-09-21
  • 2012-09-24
相关资源
最近更新 更多