我有一个文本框。按Enter键时,我希望它将DatagridView
选中的行更改为下一行。
到目前为止我所拥有的内容无效。
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (int)Keys.Enter)
{
save_Click(sender, e);
asd(sender, e);
}
}
private void asd(object sender, KeyPressEventArgs e)
{
SendKeys.Send("{Tab}"); //also tried enter
}
答案 0 :(得分:0)
您应该按如下方式编写代码,以便在文本框的按键事件中重复行!
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
int CurrentRow = dataGridView1.CurrentCell.RowIndex;
CurrentRow++;
if (CurrentRow < dataGridView1.Rows.Count)
{
dataGridView1.CurrentCell = dataGridView1.Rows[CurrentRow].Cells[0];
}
else
{
dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
}
}
}
答案 1 :(得分:0)
捕获回车键最好覆盖ProcessCmdKey
。
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Enter)
{
if (yourTextBox.Focused) // only when your are in the TextBox
{
advanceRow(yourDataGridView);
return false; // probably don't add new line
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
为了推进当前行,最好使用一个函数..
int advanceRow(DataGridView dgv)
{
int current = dgv.CurrentRow.Index;
if (current < dgv.Rows.Count - 1) // only if we hae not reached the bottom
{
dgv.CurrentCell = dgv[ 0, current + 1];
return current + 1;
}
return current;
}