Müsli
Müsli

Reputation: 1774

windows forms: scroll programmatically

I'm developing a windows forms application. And i have the following issue: in a form there's a panel, and in that panel i have a number of controls (just a label with a text box, the number is determined at runtime). This panel has a size that is smaller than the sum of all the controls added dynamically. So, i need a scroll. Well, the idea is: when the user open the form: the first of the controls must be focused, the the user enters a text and press enter, the the next control must be focused, and so until finished.

Well it's very probably that not all the controls fit in the panel, so i want that when a control inside the panel got focus the panel scrolls to let the user see the control and allow him to see what he is entering in the text box.

I hope to be clear.

here is some code, this code is used to generated the controls and added to the panel:

    List<String> titles = this.BancaService.ValuesTitle();
    int position = 0;
    foreach (String title in titles)
    {
         BancaInputControl control = new BancaInputControl(title);
         control.OnInputGotFocus = (c) => {
                 //pnBancaInputContainer.VerticalScroll.Value = 40;
                 //pnBancaInputContainer.AutoScrollOffset = new Point(0, c.Top);
                 // HERE, WHAT CAN I DO?
                 };
         control.Top = position;
         this.pnBancaInputContainer.Controls.Add(control);
         position += 10 + control.Height;
    }

Upvotes: 3

Views: 3000

Answers (1)

Nikola Markovinović
Nikola Markovinović

Reputation: 19356

If you set AutoScroll to true this will be taken care of automatically. As for the idea that Enter should move focus to next field, the best solution would be to execute enter as if it was TAB key in BancaInputControl:

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);

    if (e.KeyCode == Keys.Enter)
    {
        e.Handled = true;
        //  Move focus to next control in parent container
        Parent.SelectNextControl(this, true, true, false, false);
    }
}

If BancaInputControl is composite control (a UserControl containing other controls) each child control should hook up KeyDown event to this handler. It tries to move focus to next control in BancaInputControl; if it fails, moves focus to parent container's next control.

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        e.Handled = true;
        if (!SelectNextControl((Control)sender, true, true, false, false))
        {
            Parent.SelectNextControl(this, true, true, false, false);
        }
    }
}

Upvotes: 3

Related Questions