如何浏览使用箭头键在ASP.NET GridView控件(向上或向下)? [英] how to navigate (up or down) in ASP.NET gridview using arrow keys?

查看:344
本文介绍了如何浏览使用箭头键在ASP.NET GridView控件(向上或向下)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hhow使用whicle高亮当前行箭头键导航在ASP.NET gridview的(向上或向下)



我能够通过行与多达移动和使用下来的JavaScript代码和C#代码箭头键。我还实施了开始请求和结束请求JS代码保持在回发的滚动位置。



不过,我的问题是,滚动条不向上或向下移动,以显示自动突出显示的行。假设100行,我选择的第15行,但是电网的高度是喜欢的话可以只显示10行,除非我们手动移动滚动条,它不会自动移动通过箭头键显示选定的行。如何保证这种同步或知名度强调行通过移动滚动条?



我的GridView控件没有复选框。



请帮助我。它我的代码在这里:





 < ASP:GridView控件ID =gvCycles=服务器的AutoGenerateColumns =FALSE
的CssClass =网格
AllowSorting =真
ShowHeader =FALSE
ShowFooter =真
OnSelectedIndexChanged =gvDeductionList_SelectedIndexChanged
OnRowDataBound =gvDeductionList_RowDataBound的DataKeyNames =CycleIDonselectedindexchanging =gvCycles_SelectedIndexChanging

<柱体和GT;
< ASP:BoundField的数据字段=CycleID的HeaderText =CycleID
的HTMLEncode =FALSE
的SortExpression =CycleID>
< ItemStyle的CssClass =GridViewHiddenColumn/>
< / ASP:BoundField的>



我所做保持对回传的滚动位置为:

 < SCRIPT LANGUAGE =JavaScript的类型=文/ JavaScript的> 
//这个脚本是用于维护电网滚动的局部回传
变种scrollTop的;
//注册开始请求和结束请求
Sys.WebForms.PageRequestManager.getInstance()add_beginRequest(BeginRequestHandler)。
Sys.WebForms.PageRequestManager.getInstance()add_endRequest(EndRequestHandler)。
//获取DIV的滚动位置
功能BeginRequestHandler(发件人,参数){
变种M =的document.getElementById('divGrid');
scrollTop的= m.scrollTop;
}
//设置DIV的滚动位置
功能EndRequestHandler(发件人,参数){
变种M =的document.getElementById('divGrid');
m.scrollTop = scrollTop的;
}
< / SCRIPT>



另外,我有这样的KeyDown和KEYUP

 如果(e.keyCode =='38'){
的document.getElementById('<%= controlCapture.ClientID%GT;')。值= FALSE ;
的document.getElementById('<%= shiftCapture.ClientID%GT;')。值= FALSE;
//向上箭头
__doPostBack(PAGEID,上);
}
,否则如果(e.keyCode =='40'){
的document.getElementById('<%= controlCapture.ClientID%GT;')。值= FALSE;
的document.getElementById('<%= shiftCapture.ClientID%GT;')。值= FALSE;
//向下箭头
__doPostBack(PAGEID,下);



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



的Page_Load代码



 保护无效的Page_Load(对象发件人,EventArgs五)
{
如果(!的IsPostBack)//初始加载,默认日期目前FBT每年
{
dpDateFrom .DateValue = currentBT;
dpDateTo.DateValue = currentBTEnd;

Searchclick();
}
//光标键
,否则如果(的Request.Form [__ EVENTARGUMENT] ==上升||的Request.Form [__ EVENTARGUMENT] ==下)
{
串eventArgument =的Request.Form [__ EVENTARGUMENT];
INT intPayCycleId = 0;

如果(gvCycles.SelectedIndex> = 0&放大器;&安培; gvCycles.SelectedIndex< gvCycles.Rows.Count)
{
如果(eventArgument ==下)
{
如果(gvCycles.SelectedIndex< gvCycles.Rows.Count-1)
{
gvCycles.SelectedIndex + = 1;

}
}
,否则如果(eventArgument ==向上)
{
如果(gvCycles.SelectedIndex大于0)
{
gvCycles.SelectedIndex - = 1;
}
}

hdnSelectedRow.Value = gvCycles.SelectedValue.ToString()+,; //分配与选择行
SetRowsStyle(gvCycles)隐藏的价值;

如果(int.TryParse(gvCycles.SelectedRow.Cells [0]。文本,出intCycleId))
{
ShowDeductions(intCycleId,FALSE);
}
}
}
}


解决方案

有一个看看这个 SO 线程



这里的一个伟大的示例代码



更新



我刚刚看了一下代码的此处。自动滚动,如果你有一个DIV包裹GridView控件,如下图所示工作正常。 (我使用相同的代码中的此链接和刚添加的DIV与CSS样式,也因在代码改变循环的背后增加了没有在网格中显示的记录到 N'小于100

 < DIV CLASS =滚动> 
< ASP:GridView控件ID =GridView的=服务器的AutoGenerateColumns =FALSEOnRowCreated =gridView_RowCreated
的TabIndex =0网格=水平>
<柱体和GT;
< ASP:BoundField的的HeaderText =S#数据字段=SNO>
< HeaderStyle Horizo​​ntalAlign =中心VerticalAlign =中东WIDTH =50像素/>
< ItemStyle Horizo​​ntalAlign =中心VerticalAlign =中东WIDTH =50像素/>
< / ASP:BoundField的>
< ASP:BoundField的的HeaderText =随机号数据字段=rndno>
< HeaderStyle Horizo​​ntalAlign =中心VerticalAlign =中东WIDTH =150像素/>
< ItemStyle Horizo​​ntalAlign =中心VerticalAlign =中东WIDTH =150像素/>
< / ASP:BoundField的>
< ASP:BoundField的的HeaderText =日期数据字段=日期>
< HeaderStyle Horizo​​ntalAlign =中心VerticalAlign =中东WIDTH =100像素/>
< ItemStyle Horizo​​ntalAlign =中心VerticalAlign =中东WIDTH =100像素/>
< / ASP:BoundField的>
< ASP:BoundField的的HeaderText =时间数据字段=时间>
< HeaderStyle Horizo​​ntalAlign =中心VerticalAlign =中东WIDTH =100像素/>
< ItemStyle Horizo​​ntalAlign =中心VerticalAlign =中东WIDTH =100像素/>
< / ASP:BoundField的>
< /专栏>
< RowStyle的BackColor =#FFE0C0/>
< HeaderStyle背景色=#FF8000FONT-粗体=真前景色=白/>
< AlternatingRowStyle背景色=#FFC080/>
< / ASP:GridView的>
< / DIV>

和,这里的CSS

 <风格类型=文/ CSS> 
.scrollable {
高度:460像素;
宽度:100%;
溢出:汽车;
边界:0;
}
< /风格>



在这里输入的形象描述



更新2




  1. 注释你的JavaScript代码(它有一个__doPostBack,它会做回传,并且使你的滚动条来胡作非为)


  2. 注释你的的Page_Load 事件,因为你评论了你的JS代码<我们将不使用的否则,如果部分/ p>


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




的JavaScript

 <脚本类型=文/ JavaScript的> 
VAR SelectedRow = NULL;
VAR SelectedRowIndex = NULL;
VAR UPPERBOUND = NULL;
VAR下界= NULL;

的window.onload =函数()
{
UPPERBOUND = parseInt函数('<%= this.gvCycles.Rows.Count%GT;') - 1;
下界= 0;
SelectedRowIndex = -1;
}

功能SelectRow(CurrentRow和rowIndex)
{
如果(SelectedRow == || CurrentRow和rowIndex位置GT; UPPERBOUND ||的rowIndex<下界)回报;

如果(SelectedRow!= NULL)
{
SelectedRow.style.backgroundColor = SelectedRow.originalBackgroundColor;
SelectedRow.style.color = SelectedRow.originalForeColor;
}

如果(CurrentRow!= NULL)
{
CurrentRow.originalBackgroundColor = CurrentRow.style.backgroundColor;
CurrentRow.originalForeColor = CurrentRow.style.color;
CurrentRow.style.backgroundColor ='#DCFC5C';
CurrentRow.style.color ='黑';
}

SelectedRow = CurrentRow;
SelectedRowIndex = rowIndex位置;
的setTimeout(SelectedRow.focus();,0);
}

功能SelectSibling(五)
{
变种E =ê? E:window.event;
VAR邀请码= e.which? e.which:e.keyCode;

如果(邀请码== 40)
SelectRow(SelectedRow.nextSibling,SelectedRowIndex + 1);
,否则如果(邀请码== 38)
SelectRow(SelectedRow.previousSibling,SelectedRowIndex - 1);

返回false;
}
< / SCRIPT>



代码隐藏



 保护无效gvCycles_RowCreated(对象发件人,GridViewRowEventArgs E)
{
如果(e.Row.RowType == DataControlRowType.DataRow&放大器;及(如Row.RowState == || DataControlRowState.Normal == e.Row.RowState DataControlRowState.Alternate))
{
e.Row.TabIndex = -1;
e.Row.Attributes [的onclick] =的String.Format(JavaScript的:SelectRow(这一点,{0});,e.Row.RowIndex);
e.Row.Attributes [的onkeydown] =JavaScript的:返回SelectSibling(事件);;
e.Row.Attributes [得到聚焦] =JavaScript的:返回false;;
}
}



希望这有助于。


Hhow to navigate (up or down) in ASP.NET gridview using arrow keys whicle highlighting the current row?

I am able to move through rows with up and down arrow keys using javascript code and C# code. I also implemented a begin request and end request JS code for maintaining scroll position on postback.

However, my problem is, scrollbar doesn't move up or down to show the highlighted row automatically. Suppose 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. How to ensure this synchronous or visibility of highlighted row by moving scroll bar?

My gridview doesn't have checkbox.

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

 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

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

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. (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)

<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

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

UPDATE 2

  1. Comment your JavaScript code (It has a __doPostBack, which will do a postback and that causes your scroll bar to misbehave)

  2. comment the else if section of your Page_Load event, which we'll not be using since you commented your JS code

  3. Now add following code to your page

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.

这篇关于如何浏览使用箭头键在ASP.NET GridView控件(向上或向下)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆