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;
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;
}
}
if (CurrentColumn == colCount &&
CurrentRow != this.Rows.Count - 1)
{
base.ProcessDataGridViewKey(new KeyEventArgs(Keys.Home));
base.ProcessDataGridViewKey(new KeyEventArgs(Keys.Down));
}
else
{
base.ProcessDataGridViewKey(new KeyEventArgs(Keys.Right));
}
}
}
}