Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Move Selection Left to Right OnKeyDown Event in DataGridView.

4.00/5 (1 vote)
15 Jun 2012CPOL 9.4K  
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.

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