我(我是c#的新手)遇到了一个问题,我试图解决自己,但找不到解决方案。
给定:我有一个数据视图与10列和x行。(列头从1到10)
我的问题:我只需要写"1", "0"或"=";插入单元格,但为了在使用Numpad时更快地填充速度,我想自动写入"="当我按Numpad上的2键时,进入当前选定的单元格。
我当前的解决方案(不工作):
private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == '2'||e.KeyChar.ToString() == "2")
{
dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[dataGridView1.CurrentCell.ColumnIndex].Value = "=";
}
}
我已经尝试了它与cellLeave和cellstatchanged,但它不工作
您没有回复我的评论,但我猜这不起作用,因为事件没有被捕获。当datagridview处于编辑模式时,单元格编辑控件接收键事件,而不是datagridview。
尝试为editingcontrolshow事件添加事件处理程序,然后使用事件参数的control属性为其关键事件添加事件处理程序。
如
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
var ctrl = e.Control as TextBox;
if (ctrl == null) return;
ctrl.KeyPress += Ctrl_KeyPress;
}
private void Ctrl_KeyPress(object sender, KeyPressEventArgs e)
{
// Check input and insert values here...
}
您可以使用DataGridView尝试此方法。KeyDown事件:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.NumPad2) {
this.CurrentCell.Value = "=";
}
}
参考下面的代码:
if (e.KeyChar == (char)Keys.NumPad2 || e.KeyChar == (char)Keys.Oem2)
{
dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[dataGridView1.CurrentCell.ColumnIndex].Value = "=";
}