Click here to Skip to main content
15,905,616 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 85.2K   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

 
GeneralBetter post it as TIP/Tricks Pin
ThatsAlok16-Sep-10 0:51
ThatsAlok16-Sep-10 0:51 
GeneralRe: Better post it as TIP/Tricks Pin
Brij17-Sep-10 2:09
mentorBrij17-Sep-10 2:09 

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.