Click here to Skip to main content
14,243,279 members

Move Selection Left to Right OnKeyDown Event in DataGridView.

Rate this:
4.00 (1 vote)
Please Sign up or sign in to vote.
4.00 (1 vote)
15 Jun 2012CPOL
How to move selection from left to right instead of top to bottom which is the default functionality of DataGridView.

Introduction

Code below shows how you can move selection from left to right  instead of top to bottom which is the default functionality of DataGridView. It is useful if you want to enter a complete information of single customer before moving to the other e.g., CustomerID, CustomerName, CustomerAdress, etc.

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace DGV
{
    public class DGV : DataGridView
    {
      
        private  bool moveLeftToRight = false;     

        public bool MoveLeftToRight
        {
            get { return moveLeftToRight; }
            set { moveLeftToRight = value; }      
        }

        
        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (moveLeftToRight)
            {

                if (e.KeyCode  == Keys.Enter)
                {                    
                       MoveToNextCell();
                }
                else
                {
                    base.OnKeyDown(e);
                }
            }
            else
            {
                base.OnKeyDown(e);
            }
        }


        protected void MoveToNextCell()
        {
            int CurrentColumn, CurrentRow;

            //get the current indicies of the cell
            CurrentColumn = this.CurrentCell.ColumnIndex;
            CurrentRow = this.CurrentCell.RowIndex;

            int colCount = 0;

            for (int i = 0; i < this.Columns.Count; i++)
            {
                if (this.Columns[i].Visible == true)
                {
                    colCount = i; //Get the last visible column.
                }
            }        

            if (CurrentColumn == colCount  &&
                CurrentRow != this.Rows.Count - 1)
                //cell is at the end move it to the first cell of the next row
            {
                base.ProcessDataGridViewKey(new KeyEventArgs(Keys.Home));
                base.ProcessDataGridViewKey(new KeyEventArgs(Keys.Down));
            }
            else // move it to the next cell
            {               
                    base.ProcessDataGridViewKey(new KeyEventArgs(Keys.Right));
            }
        }
    }
}

License

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

Share

About the Author

Qadeer Ahmed Khan
Software Developer
Pakistan Pakistan
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
Tip/Trick
Posted 15 Jun 2012

Stats

7.8K views
3 bookmarked