未正确选择重新调整的DatagridView列

时间:2014-10-19 18:11:03

标签: c# datagridview

我在这里做了一个样本Download sample project from here。当我重新调整同一列时,重新排列的列未正确选择。这里的列是随机选择的。请更正此代码。

1 个答案:

答案 0 :(得分:0)

您可以存储引发MouseDown的列,然后在MouseUp事件中选择它:

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.MouseUp += dataGridView1_MouseUp;
}

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;
    }
}

private void dataGridView1_MouseUp(object sender, MouseEventArgs e)
{
    if (columnToMove != null)
    {
        dataGridView1.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
        columnToMove.Selected = true;
    }
}

修改
示例项目:download