Datagridview - 如何设置所选行的箭头?

时间:2018-02-05 10:33:24

标签: c# datagridview datasource swap

我有一个DataGridView,我已经为行创建了MoveUp和MoveDown的函数。但是当我交换两行并更改所选行时,虽然我在交换行上设置了所选行,但所选行的箭头仍保留在前一个位置。我可以更改正确行上的箭头吗?这只是一个小细节,但我想知道是否可以这样做。

我有这段代码:

    private void moveUp()
    {
        if (dataGridView1.RowCount > 0)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                int rowCount = dataGridView1.Rows.Count;
                int index = dataGridView1.SelectedCells[0].OwningRow.Index;
                if (index == 0)
                {
                    return;
                }
                var temp = listApp[index];
                var temp2 = listApp[index - 1];
                listApp.Remove(temp);
                listApp.Remove(temp2);
                listApp.Insert(index-1, temp);
                listApp.Insert(index, temp2);
                dataGridView1.DataSource = null;
                dataGridView1.DataSource = listApp;
                dataGridView1.SelectedCells[0].Selected = false;
                //dataGridView1.Rows[index].Selected = false;
                dataGridView1.Rows[index-1].Selected = true;
            }
        }
    }

交换两行后的屏幕。 enter image description here

或者有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

好的,我自己找到了一个解决方案。设置dataGridView1.CurrentCell就足够了。也许对某人有用。 解决方案在这里:

    private void moveUp()
    {
        if (dataGridView1.RowCount > 0)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                int rowCount = dataGridView1.Rows.Count;
                int index = dataGridView1.SelectedCells[0].OwningRow.Index;
                if (index == 0)
                {
                    return;
                }
                var temp = listApp[index];
                var temp2 = listApp[index - 1];
                listApp.Remove(temp);
                listApp.Remove(temp2);
                listApp.Insert(index-1, temp);
                listApp.Insert(index, temp2);
                dataGridView1.DataSource = null;
                dataGridView1.DataSource = listApp;
                dataGridView1.SelectedCells[0].Selected = false;                    
                dataGridView1.Rows[index-1].Selected = true;
                dataGridView1.CurrentCell = dataGridView1[1, index - 1];
            }
        }
    }