M. X
M. X

Reputation: 1347

Winforms: Dynamic TextBox width in FlowLayoutPanel

I have a Winforms FlowLayoutPanel with several textboxes. Is it possible that the textboxes can change their width dynamically dependent on the input of the user, so that the whole input is always displayed for each textbox?

Upvotes: 0

Views: 992

Answers (2)

Luis Miguel
Luis Miguel

Reputation: 777

in case of the textbox get's wider then the FlowLayoutPanel's just set to true the

TextBox.MultiLine to true don't forget to check the height from the textboxes comparing to the layoutpanel as well

Upvotes: 1

LarsTech
LarsTech

Reputation: 81620

You can use the TextChanged event for your TextBoxes to measure the text and set the width of the control. I added a minimum width of 32 in this example to make it practical to the end user:

public Form1() {
  InitializeComponent();

  textBox1.MinimumSize = new Size(32, 0);
  textBox2.MinimumSize = new Size(32, 0);
  textBox3.MinimumSize = new Size(32, 0);

  textBox1.TextChanged += textBox_TextChanged;
  textBox2.TextChanged += textBox_TextChanged;
  textBox3.TextChanged += textBox_TextChanged;
}

void textBox_TextChanged(object sender, EventArgs e) {
  TextBox tb = sender as TextBox;
  if (tb != null) {
    tb.Width = TextRenderer.MeasureText(tb.Text, tb.Font, Size.Empty, 
                            TextFormatFlags.TextBoxControl).Width + 8;
  }
}

There is an obvious limitation that the width of the TextBox shouldn't be wider than the FlowLayoutPanel's client width, so you would have to account for that. The + 8 for the width is just a fudge number to account for the extra spacing of padding and borders, etc.

Upvotes: 2

Related Questions