我有一个形式与datagridview的,并且当用户开始在第一行第一单元格中输入值,也可以按F2其提交值,但我不能接入小区值,除非用户打标签并转到另一个小区

以下是我的访问单元格值时F2被命中代码

 protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        var key = new KeyEventArgs(keyData);

        ShortcutKey(this, key);

        return base.ProcessCmdKey(ref msg, keyData);
    }


    protected virtual void ShortcutKey(object sender, KeyEventArgs key)
    {
        switch (key.KeyCode)
        {
            case Keys.F2:
                MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());
                break;
        }
    }

dataGridView1.SelectedCells [0]。价值返回null

有帮助吗?

解决方案 2

@BFree感谢您的代码启发了我;)为什么不直接调用this.dataGridView1.EndEdit(); MessageBox.Show之前(dataGridView1.SelectedCells [0] .Value.ToString());

此代码工作得很好:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        var key = new KeyEventArgs(keyData);

        ShortcutKey(this, key);

        return base.ProcessCmdKey(ref msg, keyData);
    }


    protected virtual void ShortcutKey(object sender, KeyEventArgs key)
    {
        switch (key.KeyCode)
        {
            case Keys.F2:
dataGridView1.EndEdit();
                MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());
                break;
        }
    }

其他提示

如何做这样的东西来代替。钩到DataGridView中的“EditingControlShowing”事件,并捕获F2那里。一些代码:

public partial class Form1 : Form
{
    private DataTable table;
    public Form1()
    {
        InitializeComponent();
        this.dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(HandleEditingControlShowing);
        this.table = new DataTable();
        table.Columns.Add("Column");
        table.Rows.Add("Row 1");
        this.dataGridView1.DataSource = table;
    }


    private void HandleEditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        var ctl = e.Control as DataGridViewTextBoxEditingControl;
        if (ctl == null)
        {
            return;
        }

        ctl.KeyDown -= ctl_KeyDown;
        ctl.KeyDown += new KeyEventHandler(ctl_KeyDown);

    }

    private void ctl_KeyDown(object sender, KeyEventArgs e)
    {
        var box = sender as TextBox;
        if (box == null)
        {
            return;
        }

        if (e.KeyCode == Keys.F2)
        {
            this.dataGridView1.EndEdit();
            MessageBox.Show(box.Text);
        }
    }

}

的想法是简单,你钩到EditingControlShowing事件。一个单元格进入编辑模式,每一次,那被炒鱿鱼。最酷的是,它暴露了实际的底层控制,你可以将它转换为实际的WinForms控制,并挂接到它的所有事件,你通常会。

您可以试试这个

string str = dataGridView.CurrentCell.GetEditedFormattedValue
             (dataGridView.CurrentCell.RowIndex, DataGridViewDataErrorContexts.Display)
             .ToString();

有对于OnKeyDown一个DataGridViewCell处理程序:

http://msdn.microsoft的.com / EN-US /库/ system.windows.forms.datagridviewcell.onkeydown.aspx

然而,唯一的问题是,你将不得不创建一个基于DataGridViewTextBoxCell来获得预期的功能自定义的细胞。因为没有暴露于该处理程序事件。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top