拖拽改变DataGridView的行顺序

DataGridView并没有属性可以设置改变行顺序,需要做如下操作,假设改变dataGridView2的行顺序,

定义全局变量记录最后一次选中的行号:

int selectionIdx = 0;

在DragEnter事件中添加如下代码:

private void dataGridView2_DragEnter(object sender, DragEventArgs e)

{

    e.Effect = DragDropEffects.Move;

}

在CellMouseMove事件中添加如下代码:

private void dataGridView2_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)

{

if ((e.Clicks < 2) && (e.Button == MouseButtons.Left))

{

if ((e.ColumnIndex == -1) && (e.RowIndex > -1))

dataGridView2.DoDragDrop(dataGridView2.Rows[e.RowIndex], DragDropEffects.Move);

}

}

在DragDrop事件中添加如下代码:

private void dataGridView2_DragDrop(object sender, DragEventArgs e)

{

int idx = GetRowFromPoint(e.X, e.Y);

 

if (idx < 0) return;

 

if (e.Data.GetDataPresent(typeof(DataGridViewRow)))

{

DataGridViewRow row = (DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow));

dataGridView2.Rows.Remove(row);

selectionIdx = idx;

dataGridView2.Rows.Insert(idx, row);

}

}

private int GetRowFromPoint(int x, int y)

{

for (int i = 0; i < dataGridView2.RowCount; i++)

{

Rectangle rec = dataGridView2.GetRowDisplayRectangle(i, false);

 

if (dataGridView2.RectangleToScreen(rec).Contains(x, y))

return i;

}

 

return -1;

}

在RowsAdded事件中添加如下代码:

private void dataGridView2_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)

{

if (selectionIdx > -1)

{

dataGridView2.Rows[selectionIdx].Selected = true;

dataGridView2.CurrentCell = dataGridView2.Rows[selectionIdx].Cells[0];

}

}

通过上面的设置即可完成拖动来改变行顺序。

注意:此方法要求dataGridView2数据不能是绑定的,必须是静态添加进去的。

可以通过如下方式给添加数据:

dataGridView2.Rows.Clear();

StringBuilder sql = new StringBuilder();

sql.Append("select * from BAS_UserStandard ");

DataTable dt = SqlProxy.GetData(sql.ToString());

if (dt.Rows.Count > 0)

{

int N = dt.Columns.Count;

for (int col_index = 0; col_index < N; col_index++)

 {

     dataGridView2.Columns.Add(dt.Columns[col_index].ColumnName, dt.Columns[col_index].ColumnName);

 }

 

    foreach (DataRow item in dt.Rows)

    {

        int index = dataGridView2.Rows.Add();

        for (int col_index = 0; col_index < N; col_index++)

        {

            dataGridView2.Rows[index].Cells[col_index].Value = item[col_index];

        }

    }

}

你可能感兴趣的:(Winform,程序人生)