在按键或按键事件 C# 中从 DataGridView 的当前列获取值

get values fron current column of DataGridView on keypress or keydown event C#

问题:我想在 datagridview 的单元格中插入字符(AccountID),以便我可以从数据库中获取相应的用户名。 我遇到的问题是,在 datagridview 的按键事件中,它最近没有插入字符。例如,如果用户名为 'John Snow',则其 ID=JN。当我在 datagridview 单元格中写入 'J' 并在按键上获取值时,它会获取“”。当我进一步写成 'JN' 时,它会变成 'J'。同样,在 'JNE' 上,它得到 'JN' ,然后我从数据库中得到 JohnSnow。简而言之,它获取最近未插入的先前值。 我已将其实施为,

    public DebitCredit()
    {
        InitializeComponent();
        this.KeyPreview = true;
        this.KeyPress += new KeyPressEventHandler(Control_KeyPress);
    }

    private void Control_KeyPress(object sender, KeyPressEventArgs e)
    {
        //Get the column and row position of the selected cell
        int column = DGV_DEBIT_CREDIT.CurrentCellAddress.X;
        int row = DGV_DEBIT_CREDIT.CurrentCellAddress.Y;
        DataTable result=null;
        if (column == 0)
        {
            string test = DGV_DEBIT_CREDIT[column, row].EditedFormattedValue.ToString();        
            result = getpro.SearchAccountByID(test);
            if (result != null)
            {
                if (result.Rows.Count > 0)
                {
                    DGV_DEBIT_CREDIT[column, row].Value = result.Rows[0][0].ToString();
                    DGV_DEBIT_CREDIT[column + 1, row].Value = result.Rows[0][1].ToString();
                }
                else
                {
                    DGV_DEBIT_CREDIT[column, row].Value = "".ToString();
                    DGV_DEBIT_CREDIT[column + 1, row].Value = "".ToString();
                }
            }
        }
    }

首先处理 DataGridViewEditingControlShowing 事件,如下所示。对于在 datagridview 列中编辑的当前控件,处理 keyUp 事件,如下所示。 然后就可以看到预期的结果了

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    e.Control.KeyUp +=   new KeyEventHandler(Control_KeyUp);
}

private void Control_KeyUp(object sender, KeyEventArgs e)
{
    //YOUR LOGIC
    // string test = dataGridView1[0, 0].EditedFormattedValue.ToString();
}