Click here to Skip to main content
16,019,593 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
4.53/5 (15 votes)
2 Aug 2011CPOL2 min read 87K   2.1K   35   27
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

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

C#
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.

JavaScript
//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:

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


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

Comments and Discussions

 
QuestionReally great work on the Manjunath! Pin
Ken LeBlanc22-Jun-16 9:37
Ken LeBlanc22-Jun-16 9:37 
QuestionUp and down navigation doesn't move the scrollbar in gridview Pin
Kicha Parameshwara Ekanta Raniyar27-Oct-14 13:56
Kicha Parameshwara Ekanta Raniyar27-Oct-14 13:56 
Questionkey navigation not working Pin
svknair15-Sep-14 1:20
svknair15-Sep-14 1:20 
GeneralThanks Pin
tsansoterra7-Mar-14 16:10
tsansoterra7-Mar-14 16:10 
GeneralRe: Thanks Pin
Manjunath Shrikantiah9-Mar-14 18:29
Manjunath Shrikantiah9-Mar-14 18:29 
QuestionHow to block the moving of arrow keys to readonly columns in gridview Pin
george@8426-Feb-14 19:18
george@8426-Feb-14 19:18 
QuestionGridView column and row navigation using up/down/right and left arrows Pin
Member 135594823-Oct-13 12:08
Member 135594823-Oct-13 12:08 
AnswerRe: GridView column and row navigation using up/down/right and left arrows Pin
Manjunath Shrikantiah24-Nov-13 23:58
Manjunath Shrikantiah24-Nov-13 23:58 
GeneralAdd jquery js file Pin
max613-May-13 6:50
max613-May-13 6:50 
QuestionArrow Key navigation Pin
devmrs25-May-12 14:47
devmrs25-May-12 14:47 
AnswerRe: Arrow Key navigation Pin
devmrs25-May-12 15:23
devmrs25-May-12 15:23 
GeneralRe: Arrow Key navigation Pin
Manjunath Shrikantiah27-May-12 18:47
Manjunath Shrikantiah27-May-12 18:47 
QuestionRe: Arrow Key navigation Pin
sunil das12-Jun-12 22:56
sunil das12-Jun-12 22:56 
GeneralMy vote of 3 Pin
Member 817912125-Jan-12 21:33
Member 817912125-Jan-12 21:33 
GeneralRe: My vote of 3 Pin
Manjunath Shrikantiah12-Mar-12 20:31
Manjunath Shrikantiah12-Mar-12 20:31 
Questionits giving me object not found error Pin
bhavna43212-Aug-11 22:31
bhavna43212-Aug-11 22:31 
AnswerRe: its giving me object not found error Pin
Manjunath Shrikantiah2-Aug-11 22:41
Manjunath Shrikantiah2-Aug-11 22:41 
QuestionHi Pin
kjalali29-Jul-11 4:00
kjalali29-Jul-11 4:00 
AnswerRe: Hi Pin
Manjunath Shrikantiah29-Jul-11 4:42
Manjunath Shrikantiah29-Jul-11 4:42 
GeneralConsider CSS for highlighting... Pin
Chris Pretorius21-Dec-10 10:02
Chris Pretorius21-Dec-10 10:02 
GeneralRe: Consider CSS for highlighting... Pin
Manjunath Shrikantiah26-Dec-10 23:52
Manjunath Shrikantiah26-Dec-10 23:52 
GeneralIssue with dropdowns. Pin
Jonathan Hankey29-Sep-10 9:10
Jonathan Hankey29-Sep-10 9:10 
GeneralRe: Issue with dropdowns. Pin
Manjunath Shrikantiah29-Sep-10 19:22
Manjunath Shrikantiah29-Sep-10 19:22 
Generalcross-browser fix: parentElement to parentNode ... Pin
Member 334412922-Sep-10 9:51
Member 334412922-Sep-10 9:51 
GeneralRe: cross-browser fix: parentElement to parentNode ... Pin
Manjunath Shrikantiah26-Sep-10 20:56
Manjunath Shrikantiah26-Sep-10 20:56 

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

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