Suk*_*nya 11 c# datagridview winforms
朋友们,我正在使用C#处理Windows应用程序.我正在使用datagridview来显示记录.我需要的功能是当我按下"Enter"键时,焦点应该转到下一个单元格(同一行的列).如果它是网格中的最后一列,那么焦点应该转到下一行的第一列.我已经尝试过了
SendKeys.Send("{Tab}")
Run Code Online (Sandbox Code Playgroud)
在datagridview1_KeyDown和datagridview1_KeyPress事件中.但重点是对角线向下移动.请帮我解决这个问题.
Kis*_*mar 13
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
int iColumn = dataGridView1.CurrentCell.ColumnIndex;
int iRow = dataGridView1.CurrentCell.RowIndex;
if (iColumn == dataGridView1.Columncount-1)
{
if (dataGridView1.RowCount > (iRow + 1))
{
dataGridView1.CurrentCell = dataGridView1[1, iRow + 1];
}
else
{
//focus next control
}
}
else
dataGridView1.CurrentCell = dataGridView1[iColumn + 1, iRow];
}
Run Code Online (Sandbox Code Playgroud)
小智 10
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
int icolumn = dataGridView1.CurrentCell.ColumnIndex;
int irow = dataGridView1.CurrentCell.RowIndex;
if (keyData == Keys.Enter)
{
if (icolumn == dataGridView1.Columns.Count - 1)
{
dataGridView1.Rows.Add();
dataGridView1.CurrentCell = dataGridView1[0, irow + 1];
}
else
{
dataGridView1.CurrentCell = dataGridView1[icolumn + 1, irow];
}
return true;
}
else
return base.ProcessCmdKey(ref msg, keyData);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用datagridview的selectionchanged事件.在你的形式
private DataGridViewCell _celWasEndEdit;
private void datagridview_SelectionChanged(object sender, EventArgs e)
{
if (MouseButtons != 0) return;
if (_celWasEndEdit != null && datagridview.CurrentCell != null)
{
// if we are currently in the next line of last edit cell
if (datagridview.CurrentCell.RowIndex == _celWasEndEdit.RowIndex + 1 &&
datagridview.CurrentCell.ColumnIndex == _celWasEndEdit.ColumnIndex)
{
int iColNew;
int iRowNew = 0;
if (_celWasEndEdit.ColumnIndex >= datagridview.ColumnCount - 1)
{
iColNew = 0;
iRowNew = dgvItems.CurrentCell.RowIndex;
}
else
{
iColNew = _celWasEndEdit.ColumnIndex + 1;
iRowNew = _celWasEndEdit.RowIndex;
}
datagridview.CurrentCell = datagridview[iColNew, iRowNew];
}
}
_celWasEndEdit = null;
}
private void datagridview_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
_celWasEndEdit = dgvItems[e.ColumnIndex, e.RowIndex];
}
Run Code Online (Sandbox Code Playgroud)