簡體   English   中英

C# WinForms:如果按下某個鍵,我如何將特定字母寫入 datagridview 單元格?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM