user377977
user377977

Reputation: 33

c# controlling datagridview columns drag and drop operation

I have a datagridview table and I want to disable drag and drop in some specific situations.

Example:

I have 4 columns named A,B,C,D. I divide them in to 2 groups: A,B and C,D (for a user they look like 4 normal columns). Now when the user drags a column A or B, he can only drop it before C. When he drags C or D, he can only drop it after B.

I tried to detect the DisplayIndex values in the ColumnDisplayIndexChanged but this event is fired multiple times and I got an exeption that DisplayIndex is being changed or sth and I can't change it at that moment.

Is there any way to do sth like that?
Thanks in advance.

Upvotes: 2

Views: 3321

Answers (1)

Ezekiel Rage
Ezekiel Rage

Reputation: 581

The drag-and-drop starts with the DataGridView::MouseDown event. There, you can remember which column was dragged

// Get the index of the item the mouse is below.
int columnIndexFromMouseDown = dataGridView1.HitTest(e.X, e.Y).ColumnIndex;
// Get the name
string columnDragName = dataGridView1.Columns[columnIndexFromMouseDown].Name;

Remember the column name and check it against the 'drop to column' in DataGridView::DragDrop. If it can be dropped do your magic, otherwise do nothing if the column combination is incorrect.

Upvotes: 1

Related Questions