简体   繁体   English

如何使用箭头键在ASP.NET gridview中导航(向上或向下)?

[英]How to navigate (up or down) in ASP.NET gridview using arrow keys?

How to navigate (up or down) in ASP.NET gridview using arrow keys while highlighting the current row? 突出显示当前行时,如何使用箭头键在ASP.NET gridview中进行导航(向上或向下)?

I am able to move through rows with up and down arrow keys using javascript code and C# code. 我可以使用javascript代码和C#代码在带有向上和向下箭头键的行之间移动。 I also implemented a begin request and end request JS code for maintaining scroll position on postback. 我还实现了一个begin请求和end请求JS代码,以保持回发时的滚动位置。

However, my problem is, scrollbar doesn't move up or down to show the highlighted row automatically. 但是,我的问题是,滚动条不会上下移动以自动显示突出显示的行。 Suppose there are 100 rows, I select 15th row, but grid height is like it can show only 10 rows, unless we move scroll bar manually, it doesn't move automatically to display the selected row via arrow keys. 假设有100行,我选择第15行,但是网格高度就像它只能显示10行一样,除非我们手动移动滚动条,否则它不会自动移动以通过箭头键显示选定的行。 How to ensure this synchronous or visibility of highlighted row by moving scroll bar? 如何通过移动滚动条确保这种同步或突出显示行的可见性?

My gridview doesn't have checkbox. 我的gridview没有复选框。

Please help me. 请帮我。 Its my code here: 它是我的代码在这里:

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

What I did to maintain the scroll position on postback is: 我要做的是在回发时保持滚动位置是:

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

Also, I have this in the keydown and keyup 另外,我在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");

Question: I do not know where to use the code you mentioned in the codeproject such that, when I press key down or up arrow keys, it should move scroll bar automatically. 问题:我不知道在代码项目中提到的代码在哪里使用,因此,当我按下向下或向上箭头键时,它应该自动移动滚动条。 I do not have pagination. 我没有分页。

Page_load Code Page_load代码

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);
                }
            }
        }
    }

Have a look at this SO thread 看看这个SO线程

And, here's a great sample code 而且, 这是一个很棒的示例代码

UPDATE 更新

I just had a look at the code here . 我只是看了一下这里的代码。 Auto Scrolling works fine if you wrap the GridView with a DIV as shown below. 如果用如下所示的DIV包装GridView,则“自动滚动”效果很好。 (I'm using the same code as given in this link and just added the DIV with the CSS style. Also increased the no of records displayed in the grid by changing the for loop in the code behind to n < 100 ) (我使用的是与此链接中给出的代码相同的代码,只是添加了具有CSS样式的DIV。通过将后面的代码中的for循环更改for n < 100还增加了网格中显示的记录n < 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>

And, here's the CSS 而且,这是CSS

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

在此处输入图片说明

UPDATE 2 更新2

  1. Comment your JavaScript code (It has a __doPostBack, which will do a postback and that causes your scroll bar to misbehave) 注释您的JavaScript代码(它具有__doPostBack,它将执行回发操作,并导致滚动条行为异常)

  2. comment the else if section of your Page_Load event, which we'll not be using since you commented your JS code 评论您的Page_Load事件的else if部分,由于您评论了JS代码,我们将不再使用它

  3. Now add following code to your page 现在将以下代码添加到您的页面

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

Code Behind 背后的代码

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;";
        }
    }

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM