tags:

views:

1148

answers:

3

I have to create variable number of Labels and next to them TextBox controls - arranging the whole thing into a column, each line a Label and a TextBox. If the my Main window is smaller than the total height of all the TextBox controls, somehow I need a scrollbar which can scroll the list of TextBoxes. Pressing the enter key would have to take the focus to the next TextBox and also scroll in case of too many TextBoxes.

This is a rather generic problem, I guess there are already some pre-baked solutions for this.

Any advice?

+6  A: 

Use a TableLayoutPanel. You can dynamically add controls, specify their row/column, and it will maintain a scrollbar for you (with the appropriate settings). It has its quirks, but should suit for this case.

If you use the WinForms designer to place the TableLayoutPanel, then you can use it to also define the style of the columns. You can also vary the style of each row as suggested by Tcks.

To add the control with a specified row/column:

int column = 42;
int row = 7;
myTableLayoutPanel.Controls.Add(new TextBox(), column, row);
ee
A: 

Also, check the generated code of a window/usercontrol after adding some controls to it. It should give you a good idea of how this could be done dynamically. (I'm talking about the somename.cs.designer file)

Mladen Mihajlovic
+1  A: 

You can use TableLayoutPanel as container for controls (Labels and TextBoxes) and create them dynamicaly in code.

Example:

void Form1_Load( object sender, EventArgs e ) {
    const int COUNT = 10;

    TableLayoutPanel pnlContent = new TableLayoutPanel();
    pnlContent.Dock = DockStyle.Fill;
    pnlContent.AutoScroll = true;
    pnlContent.AutoScrollMargin = new Size( 1, 1 );
    pnlContent.AutoScrollMinSize = new Size( 1, 1 );
    pnlContent.RowCount = COUNT;
    pnlContent.ColumnCount = 3;
    for ( int i = 0; i < pnlContent.ColumnCount; i++ ) {
     pnlContent.ColumnStyles.Add( new ColumnStyle() );
    }
    pnlContent.ColumnStyles[0].Width = 100;
    pnlContent.ColumnStyles[1].Width = 5;
    pnlContent.ColumnStyles[2].SizeType = SizeType.Percent;
    pnlContent.ColumnStyles[2].Width = 100;

    this.Controls.Add( pnlContent );

    for ( int i = 0; i < COUNT; i++ ) {
     pnlContent.RowStyles.Add( new RowStyle( SizeType.Absolute, 20 ) );

     Label lblTitle = new Label();
     lblTitle.Text = string.Format( "Row {0}:", i + 1 );
     lblTitle.TabIndex = (i * 2);
     lblTitle.Margin = new Padding( 0 );
     lblTitle.Dock = DockStyle.Fill;
     pnlContent.Controls.Add( lblTitle, 0, i );

     TextBox txtValue = new TextBox();
     txtValue.TabIndex = (i * 2) + 1;
     txtValue.Margin = new Padding( 0 );
     txtValue.Dock = DockStyle.Fill;
     txtValue.KeyDown += new KeyEventHandler( txtValue_KeyDown );
     pnlContent.Controls.Add( txtValue, 2, i );
    }
}

void txtValue_KeyDown( object sender, KeyEventArgs e ) {
    if ( e.KeyCode == Keys.Enter ) {
     SendKeys.Send( "{TAB}" );
    }
}
TcKs