DataGridView: 'cannot convert from method group to keys

六月ゝ 毕业季﹏ 提交于 2019-12-12 05:37:11

问题


I have a WinFormApp with a datagridview and I'm trying to write a method which does something when you press enter on the selected row. For example - the gridview displays some data from my database and it has 4 columns, after you finish editing those columns the way you like, you press enter and the data will be saved in the database with the new values. Currently I have this in my Form1()

     dataGridView1.PreviewKeyDown += new PreviewKeyDownEventArgs(dataGridView1_PreviewKeyDown);

which I dont think is correct, and the method is this:

void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            // do something
        }
    }

I am fairly new to programming, so a good explanation will be really appreciated.

Thank you!


回答1:


Have you tried using the CellValueChanged event? If you have the code to update your database, it should do it automatically.

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        MessageBox.Show("Test if works"); //it works
    }

EDIT-

Alternatively, if you want it to only perform a command when enter is pressed in a selected row/column you could use something like

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if(e.ColumnIndex == 1)
           {
               MessageBox.Show("Test if works"); //it works
           }
    }



回答2:


Here, dgv is an object of DatawGridView, this event is fired only when the user changes the content of the cell. Which means, if a cell as value 'abc' and user retypes again 'abc' in the same cell, this event is not fired. Similarly, if user after editing hits the 'Escape' key on keyboard, then also, this event is not fired. It means, after editing, if user hits 'Enter/Return' key on keyboard this event is fired provided the old and new value are not the same.

private void dgv_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    //code to save your changed data
}


来源:https://stackoverflow.com/questions/45286483/datagridview-cannot-convert-from-method-group-to-keys

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