开发者

How to change the behaviour of the DataGridViewComboBoxColumn in C#?

I'm working with a data grid that contains a Combo Box Column, but editing this Combo Box (by simply clicking on it) gets annoying sometimes, since one must click at least twice to change the value of that field. I want to change that behaviour, so I thought it would be very simple: just c开发者_开发百科reate a OnMouseOver event to make the mouse-overed combo box be selected, but the only available event is the Disposed one.

Is there any way to change this behaviour?


I just dealt with the same problem, and solved it by setting the DataGridView.EditMode to EditOnEnter.

If you don't like that behaviour for all your other columns, I found this suggestion for placing in the CellEnter event:

if (DataGridView1.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn)
{
    ((DataGridViewComboBoxEditingControl)DataGridView1.EditingControl).DroppedDown = true;
}

I haven't tried it, but it looks promising. The same technique is discussed on this question.


In Winforms, there's a CellMouseEnter event (and a CellEnter event for non-mouse navigation) on the DataGridView. You can use that to set the selected cell.


The reason you are getting only the Disposed event (I think) is because you are trying to go too deep. I get only the Disposed event when I try to go all the way to dataGridView1.Columns["Column1"]...

Instead, as KeithS mentioned, you can assign the CellMouseEnter event to your DataGridView.

From there, you can do the following...

private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex==0 || e.ColumnIndex==2)
    {
        dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
        dataGridView1.BeginEdit(true);
    }
}

That if-statement is just there to show how to restrict this functionality to certain columns, in case you want that.

The first line inside the if-statement sets the current cell and the second line begins the edit process.

This is a general process that should work with any type of column you can throw into a DataGridView. The DataGridView's EditMode shouldn't matter.


This works really good. On the CellClick event of the datagridview:

void datagridview1_CellClick(object sender, .Windows.Forms.DataGridViewCellEventArgs e){if (e.ColumnIndex > 0)
        {
            W1.dGVReports.CurrentCell = W1.dGVReports.Rows[e.RowIndex].Cells[e.ColumnIndex];
            W1.dGVReports.BeginEdit(true);
            (W1.dGVReports.EditingControl as System.Windows.Forms.DataGridViewComboBoxEditingControl).DroppedDown = true;
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜