DataGridView - “Cell Selection Style” - Edit Cell

2020-08-14 10:38发布

问题:

I'm working on a WinForm client with a DataGridView control. I notice users have to click once to select the cell and again to edit it. What is the way to change this to a single click edit mode? I thought I had seen something like this before but can't remember the name.

回答1:

Well I have noticed a problem with EditMode.EditOnEnter
It biases a lot of DataGriView's default behavior, which is irritating. Among others, the edited cell stays in edited mode even when the EndEdit method is explicitly called (you are force to click on another control to make the datagridview cell lose its focus.)

The following piece of code works pretty fine as it makes you edit by single clicking on any cell and ending the edit by hitting enter or clicking outside the DGView (just as you would do in the default behavior)

Here you go :

    private void myDatagridView_MouseUp(object sender, MouseEventArgs e)
    { 
        if (e.Button == MouseButtons.Left)
        {
            hitTestInfo = myDatagridView.HitTest(e.X, e.Y);
            if (hitTestInfo.Type == DataGridViewHitTestType.Cell) 
                myDatagridView.BeginEdit(true);
            else 
                myDatagridView.EndEdit();
        }
    } 


回答2:

In the DataGridView properties: EditMode -> EditOnEnter