views:

235

answers:

2

Hi,

In the DataGridView there are rows sorted by priority (first row has the highest priority) and I want to enable the user to change the priority in the user interface. The best way to do it would be to simply drag and drop the selected row but I think the logic to implement this functionality is quite complex.

The other possible way would be to add side buttons (up and down) so the user could move the selected row up or down.

Does anyone know if there is any existing control or DataGridView setting that could enable the user to sort the rows or does it have to be implemented manually?

I would appreciate your comments about how to implement the sorting functionality.

Thank you!

A: 

You might want to detect key presses for the up and down key when an item is selected in the DataGridView, so when the user presses the down key and has an item selected in the DataGridView, the selected row will swap with the row beneath it IF there is a row beneath it.

Pieter888
A: 

Didn't test (yet) but I think it would be possible to add a hidden column containing sorting data (sequence of integers), change that data then sort by the said column.

EDIT:

Here, some quick and very dirty code (try avoiding testing on the first/last rows :p):

    private void Form1_Load(object sender, EventArgs e)
    {
        int sorter = 0;
        for (char c = 'a'; c <= 'z'; c++, sorter++)
        {
            string text = new string(c, 10);
            grid.Rows.Add(sorter, text);
        }
        grid.Sort(grid.Columns[0], ListSortDirection.Ascending);
    }

    private void btnDown_Click(object sender, EventArgs e)
    {
        int selectedIndex = grid.SelectedCells[0].RowIndex;
        int currentSorter = (int)grid.Rows[selectedIndex].Cells[0].Value;
        grid.Rows[selectedIndex].Cells[0].Value = grid.Rows[selectedIndex + 1].Cells[0].Value;
        grid.Rows[selectedIndex+1].Cells[0].Value = currentSorter;
        grid.Sort(grid.Columns[0], ListSortDirection.Ascending);
    }

    private void btnUp_Click(object sender, EventArgs e)
    {
        int selectedIndex = grid.SelectedCells[0].RowIndex;
        int currentSorter = (int)grid.Rows[selectedIndex].Cells[0].Value;
        grid.Rows[selectedIndex].Cells[0].Value = grid.Rows[selectedIndex - 1].Cells[0].Value;
        grid.Rows[selectedIndex - 1].Cells[0].Value = currentSorter;
        grid.Sort(grid.Columns[0], ListSortDirection.Ascending);
    }

The grid is unbound and has two text columns, of which the first is not visible.

Sorin Comanescu