Ralph Erdt
Ralph Erdt

Reputation: 561

DataGridView change CurrentCell while changing CurrentCell

An "Inception" Problem.

A DataGridView is bounded to a child class of an BindingList ("Sorted"). The class "Sorted" take care of ordering the data. When data in "Sorted" was changed, the "Sorted" class move the current data to the correct position. The data in the DataGridView also changes, so this is OK.

Example:

A
C
B <- current entry. 

After cell leave:

A
B
C

But.. when a user change data that causes a row move and leave the cell, the next active cell (focus) is the next cell in the same row. But I want to set the focus to the cell in the new row.

Example:

A 1
C 2
B 0 
^ focus

Press Tab / Enter:

A 1
B 0
C 2 
  ^ focus

But I want to set the focus to:

A 1
B 0
  ^ focus
C 2 

Calculating the correct cell isn't the problem (The "Sorted" list executes an event). But in which event can I set the correct CurrentCell? Every event I tried ends with a bit flickering or an Exception saying that CurrentCell could not be set here because of recursion.

Upvotes: 1

Views: 84

Answers (1)

Ralph Erdt
Ralph Erdt

Reputation: 561

A very dirty but working solution:

private DataGridViewCell ThreadCellSelect = null;
private void SetNextCell(DataGridViewCell newSelection)
{
    Thread t = new Thread(new ThreadStart(ThreadSetDGVCell));
    ThreadCellSelect = newSelection;
    t.Start();
}
private void ThreadSetDGVCell()
{
    if (this.InvokeRequired)
    {
        Thread.Sleep(1); // next time slice
        Invoke((MethodInvoker)delegate () { ThreadSetDGVCell(); });
    } else
    {
        if (ThreadCellSelect != null)
        {
            this.CurrentCell = ThreadCellSelect;
            ThreadCellSelect = null;
        }
    }
}

Upvotes: 1

Related Questions