【问题标题】:C# WinForms: How do I write a specific letter to a datagridview cell if a certain key is pressed?C# WinForms:如果按下某个键,如何将特定字母写入 datagridview 单元格?
【发布时间】:2015-07-24 09:13:05
【问题描述】:

我(我是 C# 方面的新手)遇到了一个我自己尝试解决但找不到解决方案的问题。

给定: 我有一个 10 列和 x 行的 Datagridview。 (列标题从1到10)

我的问题: 我只需要在单元格中写入“1”、“0”或“=”,但是为了在使用 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 类有一个 CurrentCell 属性。

标签: c# winforms datagridview key numpad


【解决方案1】:

你没有回复我的评论,但我猜这不起作用,因为事件没有被捕获。当datagridview处于编辑模式时,单元格编辑控件接收到key事件,而不是datagridview。

尝试为 EditingControlShowing 事件添加事件处理程序,然后使用事件 args 的 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...
    }

【讨论】:

  • //Check input ... 替换为if (e.KeyChar == '2') e.KeyChar = '=';,你就是金子了。
【解决方案2】:

您可以使用DataGridView.KeyDown 事件尝试此方法:

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.NumPad2) {
        this.CurrentCell.Value = "=";
    }
}

【讨论】:

    【解决方案3】:

    参考以下代码:

    if (e.KeyChar == (char)Keys.NumPad2 || e.KeyChar == (char)Keys.Oem2)
    {
         dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[dataGridView1.CurrentCell.ColumnIndex].Value = "=";
    }
    

    希望这对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-28
      • 2011-05-15
      • 1970-01-01
      • 2011-09-19
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 2013-05-22
      相关资源
      最近更新 更多