The code works only when i'm adding a value at first time. The problem is that when i'm going back in a previous value which i added and i'm hitting enter it selects next cell from next row, not the next right cell.
Here is my code:
private void dataGridView1_CellEndEdit(object sender, KeyEventArgs e)
{
int col = dataGridView1.CurrentCell.ColumnIndex;
int row = dataGridView1.CurrentCell.RowIndex;
if (col < dataGridView1.ColumnCount - 1)
{
col++;
}
else
{
col = 0;
row++;
}
if (row == dataGridView1.RowCount)
dataGridView1.Rows.Add();
dataGridView1.CurrentCell = dataGridView1[col, row];
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.AllowUserToAddRows = false;
dataGridView1.Rows.Add();
}
Just changed the approach completely. Created a new class, extended it with DataGridView and overrode two functions. OnKeyDown and ProcessDialogKey
Here is the code:
class CustomDataGridview : DataGridView
{
protected override bool ProcessDialogKey(Keys keyData) // Fired when key is press in edit mode
{
if (keyData == Keys.Enter)
{
MoveToRightCell();
return true;
}
return base.ProcessDialogKey(keyData);
}
protected override void OnKeyDown(KeyEventArgs e) // Fired when key is press in non-edit mode
{
if (e.KeyData == Keys.Enter)
{
MoveToRightCell();
e.Handled = true;
return;
}
base.OnKeyDown(e);
}
private void MoveToRightCell()
{
int col = this.CurrentCell.ColumnIndex;
int row = this.CurrentCell.RowIndex;
if (col < this.ColumnCount - 1)
{
col++;
}
else
{
col = 0;
row++;
}
if (row == this.RowCount)
{
this.Rows.Add();
}
this.CurrentCell = this[col, row];
}
}
After adding this class build you project and then you can simply chose this new control from Toolbox>DgvDemoComponents>CustomDataGridview Or if you want to convert the old DataGridView into a new one just change to following line:
this.dataGridView1 = new System.Windows.Forms.DataGridView();
to
this.dataGridView1 = new DgvDemo.CustomDataGridview();
The Second approach will cause some issues in designer just select ignore and proceed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.