I am working with barcode scanner. On simple text box I am handling KeyPress event by looking for Keys.Return. This help me to know that barcode reading has been completed. But when working with datagridview text boxes. Barcode reader not sending return on key press event also by default datagridview moves cursor to down after barcodede reading completion.I want to move focus of datagridview text box to next cell and not to down. How should I handle this? My current implementation is as follows:
private void dgvListItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DataGridViewTextBoxColumn textBox = (DataGridViewTextBoxColumn)dgvMeterData.Columns["MeterId"];
if (dgvMeterData.CurrentCellAddress.X == textBox.DisplayIndex)
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += tb_KeyPress;
}
}
}}
private void tb_KeyPress(object sender, KeyPressEventArgs e)
{
TextBox tb = sender as TextBox;
if (e.KeyChar==(char)Keys.Return)
{
tb.Text = tb.Text + e.KeyChar;
var columnIndex = dgvMeterData.CurrentRow.Cells["TestResults"].ColumnIndex;
var rowIndex = dgvMeterData.CurrentRow.Cells["TestResults"].RowIndex;
dgvMeterData.CurrentCell = (DataGridViewCell)dgvMeterData[columnIndex, rowIndex];
}
}
This helped me doing almost the same thing. I hope you get the idea.
private void dgvListItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewTextBoxEditingControl)
{
DataGridViewTextBoxEditingControl tb = e.Control as DataGridViewTextBoxEditingControl;
tb.PreviewKeyDown -= dgvListItems_PreviewKeyDown;
tb.PreviewKeyDown += dgvListItems_PreviewKeyDown;
}
}
private void dgvListItems_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyData == Keys.Return)
{
int columnIndex = dgvListItems.CurrentCell.ColumnIndex; ;
int rowIndex = dgvListItems.CurrentCell.RowIndex;
if (columnIndex == dgvListItems.Columns.Count - 1)
{
dgvListItems.CurrentCell = dgvListItems[0, rowIndex + 1];
}
else
{
dgvListItems.CurrentCell = dgvListItems[columnIndex + 1, rowIndex];
}
}
}