c# datagridview key handling

时光总嘲笑我的痴心妄想 提交于 2019-12-24 10:47:12

问题


I use DataGridView, and in some places I add control to it (e.g. textbox, combobox)

 dataGridView1.Controls.Add(comboBox);
 comboBox.Focus();

The problem is that using this control, and than commiting choice by using ENTER cause the DataGridView to "handle" the key -> after clickng enter instead of choosing sth from combobox, the selection in datagridview changes( moves to next cell).

I use sth like :

   public class MyDataGridView:DataGridView
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if(keyData == Keys.Enter)
        {
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

But it cause that datagridview and combobox doesn't answer to ENTER, and other keys...

Additional infromation: I must use ComboBox class, instead of DataGridViewCombobox. Can anyone help me how to handle ENTER in my comobox?


回答1:


Try:

if((keyData == Keys.Enter) && (MyComboBox.Focused))

so DataGridView responds to ENTER except when your control is focused.

I am not sure the following code fits your situation, but maybe you could try something like:

public class MyDataGridView:DataGridView
{
    public ComboBox MyComboBox { get; set; } //in case you had no other way to refer to it

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if((keyData == Keys.Enter) && (MyComboBox.Focused))
        {
            //commit choice logic
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

and from your form, if it needs, set the reference to your ComboBox:

dataGridView1.Controls.Add(comboBox);
dataGridView1.MyComboBox = comboBox;
comboBox.Focus();


来源:https://stackoverflow.com/questions/9290203/c-sharp-datagridview-key-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!