John Humphreys
John Humphreys

Reputation: 39354

DataGridView Sort - Keep two in sync

If I have two DataGridView items in a C# Win Forms application, and they have the same column set at all times, how can I ensure they are always sorted the same way?

I can get a notification when one grid or the other sorts, but if I try to use that notification to sort the other grid in the same way I get a stack overflow (for obvious reasons).

I'm sure I can get around the stack overflow problem with some ugly hacks, but I figure there must be a normal way to do this. I can't be the first one with the need to keep two DataGridViews in sync when the user's sorting them.

Upvotes: 0

Views: 538

Answers (1)

cppanda
cppanda

Reputation: 1315

I get a stack overflow (for obvious reasons).

Without sample code they might not be obvious. Do you get the Stack overflow because each update notification updates the other grid which results in a infinite loop?

then why don't you keep bools to track state like so:

bool Grid1Fired = false;
bool Grid2Fired = false;

void handler_Grid1(..)
{
    if(Grid1Fired == false && Grid2Fired == false)
    {
        Grid1Fired = true;
        SortGrids();
    }
}
void handler_Grid2(..)
{
    if(Grid1Fired == false && Grid2Fired == false)
    {
        Grid2Fired = true;
        SortGrids();
    }
}

void SortGrids()
{
    if(Grid1Fired)
    {
        // sort grid 2
    }
    else if(Grid2Fired)
    {
        // sort grid 1
    }
    Grid1Fired = false;
    Grid2Fired = false;
}

Upvotes: 1

Related Questions