Click here to Skip to main content
Licence CPOL
First Posted 16 Sep 2010
Views 18,576
Downloads 665
Bookmarked 29 times

GridView column and row navigation using up/down/right and left arrows

By | 2 Aug 2011 | Article
Implementing GridView column and row navigation using up/down/right and left arrows.

Introduction

There are times when users ask for some features in web applications similar to those in Windows applications. I have tried to cover one of them here. This article explains how you can navigate through controls in a GridView using up/down/right and left arrows. I wanted to come up with an optimal solution which can work in all major browsers. This wasn't very challenging as I initially thought. With the help of jQuery (just awesome, I have started loving this script library as I use it more and more), I was able to do it with minimal coding.

Note

I have assumed only textboxes as controls in the GridView cells. But this can be applied for other controls like dropdowns etc.

GridView Code

<asp:GridView ID="GridView1" runat="server" 
           AutoGenerateColumns="False" CellPadding="4" 
           ForeColor="#333333" GridLines="None">
    <RowStyle BackColor="#E3EAEB" />
    <Columns>
        <asp:TemplateField HeaderText="Coulumn1" 
                  HeaderStyle-HorizontalAlign="Left">
            <ItemTemplate>
                <asp:TextBox runat="server" ID="txtColumn1" 
                     Text='<%# Bind("Column1") %>'></asp:TextBox>
            </ItemTemplate>
            <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Coulumn1" 
                  HeaderStyle-HorizontalAlign="Left">
            <ItemTemplate>
                <asp:TextBox runat="server" ID="txtColumn2" 
                       Text='<%# Bind("Column2") %>'></asp:TextBox>
            </ItemTemplate>
            <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Coulumn1" HeaderStyle-HorizontalAlign="Left">
            <ItemTemplate>
                <asp:TextBox runat="server" ID="txtColumn3" 
                        Text='<%# Bind("Column3") %>'></asp:TextBox>
            </ItemTemplate>
            <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
        </asp:TemplateField>
    </Columns>
    <FooterStyle BackColor="#1C5E55" ForeColor="White" Font-Bold="True" />
    <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
    <EditRowStyle BackColor="#7C6F57" />
    <AlternatingRowStyle BackColor="White" />
</asp:GridView>

C# Code

The following code is used to generate the dummy data table and to bind it to the GridView:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindGrid(10);
    }

    private void BindGrid(int rowcount)
    {
        DataTable dt = new DataTable();
        DataRow dr;
        dt.Columns.Add(new System.Data.DataColumn("Column1", typeof(String)));
        dt.Columns.Add(new System.Data.DataColumn("Column2", typeof(String)));
        dt.Columns.Add(new System.Data.DataColumn("Column3", typeof(String)));
        for (int i = 1; i < rowcount + 1; i++)
        {
            dr = dt.NewRow();
            dr[0] = "Row" + i.ToString() + " Col1"   ;
            dr[1] = "Row" + i.ToString() + " Col2";
            dr[2] = "Row" + i.ToString() + " Col3";
            dt.Rows.Add(dr);
        }
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

GridView Output

Description: gridview1.jpg

jQuery Code

The following code is used to bind the keydown events for all the textboxes and dropdowns. Every time the user uses the arrow keys, the keydown event gets triggered. In the below code, I have assumed the page will only have textboxes and a dropdown list in the GridView. In case you have other text boxes and dropdowns in the web page outside of the GridView, ensure to select only the controls in the GridView in the jQuery code.

//JQuery Code

<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        //For navigating using left and right arrow of the keyboard
        $("input[type='text'], select").keydown(
function(event) {
    if ((event.keyCode == 39) || (event.keyCode == 9 && event.shiftKey == false)) {
        var inputs = $(this).parents("form").eq(0).find("input[type='text'], select");
        var idx = inputs.index(this);
        if (idx == inputs.length - 1) {
            inputs[0].select()
        } else {
            $(this).parents("table").eq(0).find("tr").not(':first').each(function() {
                $(this).attr("style", "BACKGROUND-COLOR: white; COLOR: #003399");
            });
            inputs[idx + 1].parentNode.parentNode.style.backgroundColor = "Aqua";
            inputs[idx + 1].focus();
        }
        return false;
    }
    if ((event.keyCode == 37) || (event.keyCode == 9 && event.shiftKey == true)) {
        var inputs = $(this).parents("form").eq(0).find("input[type='text'], select");
        var idx = inputs.index(this);
        if (idx > 0) {
            $(this).parents("table").eq(0).find("tr").not(':first').each(function() {
                $(this).attr("style", "BACKGROUND-COLOR: white; COLOR: #003399");
            });
            inputs[idx - 1].parentNode.parentNode.style.backgroundColor = "Aqua";
      
            inputs[idx - 1].focus();
        }
        return false;
    }
});
//For navigating using up and down arrow of the keyboard
$("input[type='text'], select").keydown(
function(event) {
    if ((event.keyCode == 40)) {
        if ($(this).parents("tr").next() != null) {
            var nextTr = $(this).parents("tr").next();
            var inputs = $(this).parents("tr").eq(0).find("input[type='text'], select");
            var idx = inputs.index(this);
            nextTrinputs = nextTr.find("input[type='text'], select");
            if (nextTrinputs[idx] != null) {
                $(this).parents("table").eq(0).find("tr").not(':first').each(function() {
                    $(this).attr("style", "BACKGROUND-COLOR: white; COLOR: #003399");
                });
                nextTrinputs[idx].parentNode.parentNode.style.backgroundColor = "Aqua";
                nextTrinputs[idx].focus();
            }
        }
        else {
            $(this).focus();
        }
    }
    if ((event.keyCode == 38)) {
        if ($(this).parents("tr").next() != null) {
            var nextTr = $(this).parents("tr").prev();
            var inputs = $(this).parents("tr").eq(0).find("input[type='text'], select");
            var idx = inputs.index(this);
            nextTrinputs = nextTr.find("input[type='text'], select");
            if (nextTrinputs[idx] != null) {
                $(this).parents("table").eq(0).find("tr").not(':first').each(function() {
                    $(this).attr("style", "BACKGROUND-COLOR: white; COLOR: #003399");
                });
                nextTrinputs[idx].parentNode.parentNode.style.backgroundColor = "Aqua";
                nextTrinputs[idx].focus();
            }
            return false;
        }
        else {
            $(this).focus();
        }
    }
});
});    </script>

Summary

I have tested this sample in IE 8.0, Google Chrome 5.0, and Firefox 3.0.3. Hope this helps people who are looking for navigation within a GridView using keys.

I have updated the code to highlight the row selected.

Update

The above code was refactored to make it a jQuery plug-in. You will need to include the “jquery.keynavigation.js” file in your source. Below are the only two lines of code required to get the above functionalities in your grid:

<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        //For navigating using left and right arrow of the keyboard
        var gridview = $("#GridView1");
        $.keynavigation(gridview);
    });
</script>

I have updated the sample application with a demo page called KeyNavigationPlugIn.aspx.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Manjunath Shrikantiah

Architect

India India

Member

9+ plus years of experience in IT industry. This includes experience in architecting, designing and developing solutions on Web and desktop application platforms

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionArrow Key navigation Pinmemberdevmrs14:47 25 May '12  
AnswerRe: Arrow Key navigation Pinmemberdevmrs15:23 25 May '12  
GeneralRe: Arrow Key navigation PinmemberManjunath Shrikantiah17hrs 23mins ago 
GeneralMy vote of 3 PinmemberMember 817912121:33 25 Jan '12  
GeneralRe: My vote of 3 PinmemberManjunath Shrikantiah20:31 12 Mar '12  
Questionits giving me object not found error Pinmemberbhavna432122:31 2 Aug '11  
AnswerRe: its giving me object not found error PinmemberManjunath Shrikantiah22:41 2 Aug '11  
QuestionHi Pinmemberkjalali4:00 29 Jul '11  
AnswerRe: Hi PinmemberManjunath Shrikantiah4:42 29 Jul '11  
GeneralConsider CSS for highlighting... PinmemberChris Pretorius10:02 21 Dec '10  
GeneralRe: Consider CSS for highlighting... PinmemberManjunath Shrikantiah23:52 26 Dec '10  
GeneralIssue with dropdowns. PinmemberJonathan Hankey9:10 29 Sep '10  
GeneralRe: Issue with dropdowns. PinmemberManjunath Shrikantiah19:22 29 Sep '10  
Generalcross-browser fix: parentElement to parentNode ... PinmemberMember 33441299:51 22 Sep '10  
GeneralRe: cross-browser fix: parentElement to parentNode ... PinmemberManjunath Shrikantiah20:56 26 Sep '10  
GeneralBetter post it as TIP/Tricks Pinmember ThatsAlok 0:51 16 Sep '10  
GeneralRe: Better post it as TIP/Tricks PinmentorBrij2:09 17 Sep '10  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120528.1 | Last Updated 2 Aug 2011
Article Copyright 2010 by Manjunath Shrikantiah
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid