[英]How do you input data from sql into a specific datagridview cell based on column date and name in c# winforms
[英]C# WinForms: How do I write a specific letter to a datagridview cell if a certain key is pressed?
我(我是 C# 的新手)遇到了一个我试图自己解决但找不到解决方案的问题。
给定:我有一个 10 列 x 行的 Datagridview。 (列标题从 1 到 10)
我的问题:我只需要在单元格中写入“1”、“0”或“=”,但为了在使用数字键盘时提高填充速度,我想在按下时自动将“=”写入当前选定的单元格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。
尝试为 EditingControlShowing 事件添加一个事件处理程序,然后使用事件参数的 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...
}
请参考以下代码:
if (e.KeyChar == (char)Keys.NumPad2 || e.KeyChar == (char)Keys.Oem2)
{
dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[dataGridView1.CurrentCell.ColumnIndex].Value = "=";
}
希望这对你有用。
您可以使用DataGridView.KeyDown事件尝试此方法:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.NumPad2) {
this.CurrentCell.Value = "=";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.