Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

c# - How to activate combobox on first click (Datagridview)

In winforms, you need to click the combobox twice to properly activate it - the first time to focus it, the second time to actually get the dropdown list.

How do I change this behavior so that it activates on the very first click?

This is for DATAGRIDVIEW combobox.

question from:https://stackoverflow.com/questions/13005112/how-to-activate-combobox-on-first-click-datagridview

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I realize this is an old question, but I figured I would give my solution to anyone out there that may need to be able to do this.

While I couldn't find any answers to do exactly this... I did find an answer to a different question that helped me.

This is my solution:

private void datagridview_CellEnter(object sender, DataGridViewCellEventArgs e)
    {
        bool validClick = (e.RowIndex != -1 && e.ColumnIndex != -1); //Make sure the clicked row/column is valid.
        var datagridview = sender as DataGridView;

        // Check to make sure the cell clicked is the cell containing the combobox 
        if(datagridview.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn && validClick)
        {
            datagridview.BeginEdit(true);
            ((ComboBox)datagridview.EditingControl).DroppedDown = true;
        }
    }


private void datagridview_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        datagridview.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }

The above code must be tied into the CellEnter event of the datagridview.

I hope this helps!

edit: Added a column index check to prevent crashing when the entire row is selected.

Thanks, Up All Night for the above edit

edit2: Code is now to be tied to the CellEnter rather than the CellClick event.

Thanks, HaraldDutch for the above edit

edit3: Any changes will committed immediately, this will save you from clicking in another cell in order to update the current combobox cell.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...