Click here to Skip to main content
15,892,697 members
Articles / Programming Languages / C#
Tip/Trick

Move Selection Left to Right OnKeyDown Event in DataGridView.

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
15 Jun 2012CPOL 9.3K   3  
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)


Written By
Software Developer
Pakistan Pakistan
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --