Sharanamma Jk
Sharanamma Jk

Reputation: 137

How to rearrange a WinForms Controls during runtime?

In my project I wanted to order controls at run-time, like in DataGridView how we'll use display-index to order fields in the grid.

In design level I added 3 TextBoxs and 1 ComboBox next to each other & in run time i wanted to order them, for example, first 2 TextBoxs should show, then the ComboBox and then the other TextBox.

Is it possible to rearrange the controls in run-time?

Upvotes: 1

Views: 902

Answers (1)

Moha Dehghan
Moha Dehghan

Reputation: 18443

Every Control in Windows Forms has a Location property. You can easily change the location of the control by changing this property:

textBox1.Location = new Point(10, 50); // Puts the TextBox at coordinates (10,50)

The coordinates are relative to upper-left corner of the control container (the form itself for example).

In your case, you can easily arrange the controls like this:

Control[] controls = new Control[] { textBox1, textBox2, comboBox3, textBox3 }; // These are your controls
int left = 20, top = 50; // or any other value
foreach (c in controls)
{
    c.Location = new Point(left, top);
    left += c.Width + 10; // space 10 pixels between controls
}

Upvotes: 1

Related Questions