Question

I have a C# .NET 3.0 project that uses a TableLayoutPanel containing several rows of controls. If I scroll down such that the top item is no longer visible, then remove a control in one column and replace it with a new control, the TableLayoutPanel scrolls back to the top.

/// the panel in question
private System.Windows.Forms.TableLayoutPanel impl_;

/// The user has clicked a linklabel in the panel. replace it with an edit-box
private void OnClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    LinkLabel link_label = sender as LinkLabel;
    TextBox new_edit = new TextBox();
    // setup the new textbox...

    TableLayoutPanelCellPosition pos = impl_.GetCellPosition(link_label);
    impl_.Controls.Remove(link_label);
    impl_.Controls.Add(new_edit, pos.Column, pos.Row);
    new_edit.Focus();
}

What do I need to do to keep the scroll position from changing?

Was it helpful?

Solution

You are removing the control that has the focus. It will try to find another one to give the focus to, scrolling it into view if necessary. Short from giving another control the focus, one thing that might work is adding the TextBox and giving it the focus before you remove the label.

OTHER TIPS

The solution of Hans Passant is the best for the context. But in other cases where you can't work with focus, you can use the AutoScollPosition to scroll back to the previous position:

Point scrollPosition = tlp.AutoScrollPosition;

//make changes here

tlp.AutoScrollPosition = new Point(-scrollPosition.X, -scrollPosition.Y) //according to the documentation negative coordinates are returned but positive ones need to be assigned
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top