i have created a custom datagridview and trying to move my cell to the right when i presses enter key (instead of going to down on pressing enter key ) but i found that i have to press enter twice to move rightwards . when i presses enter key first time , it still go downwards (default way) and then if i presses enter again ,then it moves to right .
public partial class Paymentdatagridview : DataGridView
{
public Paymentdatagridview()
{
// i have set enableheadervisualstyles to false
// make bold the headers
// Add the columns to your custom DataGridView
DataGridViewColumn column1 = new DataGridViewTextBoxColumn();
column1.Name = "Column1";
column1.HeaderText = "Particulars";
column1.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
column1.SortMode = DataGridViewColumnSortMode.Automatic;
this.Columns.Add(column1);
DataGridViewColumn column2 = new DataGridViewTextBoxColumn();
column2.Name = "Column2";
column2.HeaderText = "Amount";
column2.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
column2.SortMode = DataGridViewColumnSortMode.Programmatic;
this.Columns.Add(column2);
this.AllowUserToAddRows = true;
this.RowHeadersVisible = false;
this.ColumnHeadersDefaultCellStyle.Font = new Font("Tahoma", 9.75F, FontStyle.Bold);
this.CellBorderStyle = DataGridViewCellBorderStyle.None;
InitializeComponent();
}
protected override void OnEnter(EventArgs e)
{
// Set the current cell to the first cell and enable editing when the control receives focus
if (RowCount > 0 && ColumnCount > 0)
{
CurrentCell = Rows[0].Cells[0];
BeginEdit(true);
}
base.OnEnter(e);
}
protected override bool ProcessDataGridViewKey(KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// Move the focus to the next column and row when Enter key is pressed
if (CurrentCell.ColumnIndex == ColumnCount - 1)
{
if (CurrentCell.RowIndex == RowCount - 1)
{
// Reached the last cell, move focus to the first cell
CurrentCell = Rows[0].Cells[0];
}
else
{
// Move to the first cell of the next row
CurrentCell = Rows[CurrentCell.RowIndex + 1].Cells[0];
}
}
else
{
// Move to the next column
CurrentCell = Rows[CurrentCell.RowIndex].Cells[CurrentCell.ColumnIndex + 1];
}
BeginEdit(true);
e.Handled = true;
return true;
}
return base.ProcessDataGridViewKey(e);
}
}