DataGridView Selected Row Move UP and DOWN

后端 未结 13 1492
盖世英雄少女心
盖世英雄少女心 2020-12-06 01:31

How can I allow selected rows in a DataGridView (DGV) to be moved up or down. I have done this before with a ListView. Unfortunetly, for me, replacing the DGV is not an opt

13条回答
  •  庸人自扰
    2020-12-06 02:07

    Just to expand on Yoopergeek's answer, here's what I have. I was not using a DataSource (data is being dropped to registry on form close, and reload on form load)

    This sample will keep rows from being moved off the grid and lost, and reselect the cell the person was in as well.

    To make things simpler for copy / paste, I modified so you need only change "gridTasks" to your DataGridView's name, rather than renaming it throughout the code.

    This solution works only for single cell/row selected.

    private void btnUp_Click(object sender, EventArgs e)
    {
        DataGridView dgv = gridTasks;
        try
        {
            int totalRows = dgv.Rows.Count;
            // get index of the row for the selected cell
            int rowIndex = dgv.SelectedCells[ 0 ].OwningRow.Index;
            if ( rowIndex == 0 )
                return;
            // get index of the column for the selected cell
            int colIndex = dgv.SelectedCells[ 0 ].OwningColumn.Index;
            DataGridViewRow selectedRow = dgv.Rows[ rowIndex ];
            dgv.Rows.Remove( selectedRow );
            dgv.Rows.Insert( rowIndex - 1, selectedRow );
            dgv.ClearSelection();
            dgv.Rows[ rowIndex - 1 ].Cells[ colIndex ].Selected = true;
        }
        catch { }
    }
    
    private void btnDown_Click(object sender, EventArgs e)
    {
        DataGridView dgv = gridTasks;
        try
        {
            int totalRows = dgv.Rows.Count;
            // get index of the row for the selected cell
            int rowIndex = dgv.SelectedCells[ 0 ].OwningRow.Index;
            if ( rowIndex == totalRows - 1 )
                return;
            // get index of the column for the selected cell
            int colIndex = dgv.SelectedCells[ 0 ].OwningColumn.Index;
            DataGridViewRow selectedRow = dgv.Rows[ rowIndex ];
            dgv.Rows.Remove( selectedRow );
            dgv.Rows.Insert( rowIndex + 1, selectedRow );
            dgv.ClearSelection();
            dgv.Rows[ rowIndex + 1 ].Cells[ colIndex ].Selected = true; 
        }
        catch { }
    }
    

提交回复
热议问题