如何获得一个DataGridView列的索引mouseUp事件,而不是在一个MouseDown事件?

2019-10-21 03:53发布

我有一个WinForm DataGridView ,我的目标是拖动一列,将其放到其他列索引。 我知道重新排序列,可以通过使用AllowUserToOrderColumns = true 。 但我要对DGV执行其他操作。 这就是为什么我需要在鼠标向上事件的目标列的索引。 要做到这一点,我用HitTestInfo

System.Windows.Forms.DataGrid.HitTestInfo myHitTest;
myHitTest = dataGrid1.HitTest(e.X, e.Y);
int p = myHitTest.ColumnIndex;

当我点击第一列DGV,运行此代码,给我列的索引( p )。 问题是,当我把它放在DGV的另一列,我想知道目标列的索引,使用相同的代码p = -1 ,我想是因为HitTestInfo构件上的返回值MouseDown不是一个MouseUp 。 如果有人能告诉我如何做到这一点,那将是非常巨大的。

Answer 1:

您可以创建两个HitTestInfo对象,一个在MouseDown ,一个在MouseUp

海事组织,你也应该使用DataGridView.HitTestInfo类,而不是DataGrid.HitTestInfo并尽量不叫或名称DataGridViews DataGrids ,这是从类似,但不同的控制WPF

DataGridView.HitTestInfo myHitTestDown, myHitTestUp;
int visibleColumnDown, visibleColumnUp;

private void dataGrid1_MouseUp(object sender, MouseEventArgs e)
{
    myHitTestUp = dataGrid1.HitTest(e.X, e.Y);
    visibleColumnUp = getVisibleColumn(dataGrid1, e.X);
}

private void dataGrid1_MouseDown(object sender, MouseEventArgs e)
{
    myHitTestDown = dataGrid1.HitTest(e.X, e.Y);
    visibleColumnDown = getVisibleColumn(dataGrid1, e.X);
}

更新:要查找后列已重新排序,只需使用一列的可见指数:

dataGrid1.Columns[myHitTestUp.ColumnIndex].DisplayIndex;

之前,我发现,我写了这个小帮手功能,这不相同:

int getVisibleColumn(DataGridView dgv, int x)
{
    int cx = dgv.RowHeadersWidth;
    int c = 0;
    foreach (DataGridViewColumn col in dgv.Columns)
    {
        cx += col.Width; if ( cx >= x) return c; c++;
    }
    return -1;
}

要找出哪一列是被洗牌似乎有点困难。 有一个事件,它被调用为每个 受到影响 ,它总是最先被称为该被拖着的一列。 下面是做这件事:

建立在类级别的变量:

List<DataGridViewColumn> shuffled = new List<DataGridViewColumn>();
DataGridViewColumn shuffledColumn = null;

还记得第一列:

private void dgvLoadTable_ColumnDisplayIndexChanged(
             object sender, DataGridViewColumnEventArgs e)
{
    if (shuffledColumn == null) shuffledColumn = e.Column;
}

忘记之前发生了什么:

private void dgvLoadTable_MouseDown(object sender, MouseEventArgs e)
{  
    shuffledColumn = null;
}

现在你可以使用它。 选择列,然而,不与他们洗牌顺利! 如果你这样做

 shuffledColumn.Selected = true;

如果它只会被选中SelectionMode或者是FullColumnSelectColumnHeaderSelect -在这两种模式下,洗牌是行不通的,我怕..



Answer 2:

您可以使用拖放了点。
假设你有一个FormDataGridView名为dataGridView1

最初,不要忘了让拖放为DataGridView

dataGridView1.AllowDrop = true;

事件处理程序将取代所需功能MouseUp将是dataGridView1_DragDrop ,目标列的索引是colIndexOfItemUnderMouseToDrop

private Rectangle dragBoxFromMouseDown;
private int colIndexFromMouseDown;

private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
    if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
    {
        // If the mouse moves outside the rectangle, start the drag.
        if (dragBoxFromMouseDown != Rectangle.Empty &&
            !dragBoxFromMouseDown.Contains(e.X, e.Y))
        {
            // Proceed with the drag and drop, passing in the list item.                    
            dataGridView1.DoDragDrop(colIndexFromMouseDown, DragDropEffects.Move);
        }
    }
}

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
    // Get the index of the item the mouse is below.
    colIndexFromMouseDown = dataGridView1.HitTest(e.X, e.Y).ColumnIndex;

    if (colIndexFromMouseDown != -1)
    {
        // Remember the point where the mouse down occurred. 
        // The DragSize indicates the size that the mouse can move 
        // before a drag event should be started.                
        Size dragSize = SystemInformation.DragSize;

        // Create a rectangle using the DragSize, with the mouse position being
        // at the center of the rectangle.
        dragBoxFromMouseDown = new Rectangle(
            new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)),
            dragSize);
    }
    else
        // Reset the rectangle if the mouse is not over an item in the ListBox.
        dragBoxFromMouseDown = Rectangle.Empty;
}

private void dataGridView1_DragOver(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.Move;
}

private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
    // If the drag operation was a move then remove and insert the column.
    if (e.Effect == DragDropEffects.Move)
    {
        // The mouse locations are relative to the screen, so they must be 
        // converted to client coordinates.
        Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));

        // Get the column index of the item the mouse is below. 
        int colIndexOfItemUnderMouseToDrop = dataGridView1.HitTest(clientPoint.X, clientPoint.Y).ColumnIndex;
        if (colIndexOfItemUnderMouseToDrop == -1)
            return;
        colIndexOfItemUnderMouseToDrop = dataGridView1.Columns[colIndexOfItemUnderMouseToDrop].DisplayIndex;
        // Now we have the column's display index.

        if (e.Data.GetDataPresent(typeof(int)))
        {
            int colToMove = (int)e.Data.GetData(typeof(int));
            dataGridView1.Columns[colToMove].DisplayIndex = colIndexOfItemUnderMouseToDrop;
            // Select the column:
            dataGridView1.Columns[colToMove].Selected = true;
        }
    }
}

编辑
新的方法:

private DataGridViewColumn columnToMove;

public Form1()
{
    InitializeComponent();

    dataGridView1.Columns.AddRange(new DataGridViewColumn[]
        {
            new DataGridViewTextBoxColumn { Name = "AAA", SortMode = DataGridViewColumnSortMode.NotSortable },
            new DataGridViewTextBoxColumn { Name = "BBB", SortMode = DataGridViewColumnSortMode.NotSortable },
            new DataGridViewTextBoxColumn { Name = "CCC", SortMode = DataGridViewColumnSortMode.NotSortable }
        });
    dataGridView1.Rows.Add(2);
    dataGridView1.AllowUserToOrderColumns = true;
    dataGridView1.MouseDown += dataGridView1_MouseDown;
    dataGridView1.ColumnDisplayIndexChanged += dataGridView1_ColumnDisplayIndexChanged;
}

private void dataGridView1_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
{
    if (e.Column == columnToMove)
    {
        dataGridView1.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
        e.Column.Selected = true;
    }
}

private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
    var hti = dataGridView1.HitTest(e.X, e.Y);
    if (hti.Type == DataGridViewHitTestType.ColumnHeader)
    {
        columnToMove = dataGridView1.Columns[hti.ColumnIndex];
        dataGridView1.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
    }
}


文章来源: How to get a DataGridView column's index in a MouseUp event, not in a MouseDown event?