简体   繁体   中英

User Control Label and Textbox flow from right to left

It was pretty tough to think a title for this question so I'll try to make a better job explaining myself here.

I needed to create a dynamic Windows Form so that when checkbox gets checked/unchecked, few input fields appear/disappear. As far as I know FlowLayoutPanel seemed to be the best tool to achieve this. So I created a Custom User Control that included a Label and a Textbox. I designed this new Control in VS2013 desginer view:

自定义用户控件

Since the text on the label can vary in length it is important that textbox begins only when label has already ended. However the result I get at the moment looks like this:

实际的自定义用户控件

The label should read out "ConnField" instead of "ConnFie". I tried adding these items in FlowLayoutPanel but that resulted in label and textbox not lining up correctly. Are there any attributes/properties that should be set in order to get the expected result? Should I use a container that does it all for me?

On a side note, if there are any other methods to dynamically show/hide elements in the fashion I described above I'd be very happy to use those instead.

For perfect fits you can script the TextChanged event(s) to make sure the TextBox always sits in place and keeps a nice size as well..

I have placed a Label and a TextBox into a Panel for testing. You will probaly not need or want the textBox1_TextChanged event but it was nice for testing..:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    label1.Text = textBox1.Text;   // this is for testing
}

private void label1_TextChanged(object sender, EventArgs e)
{
    textBox1.Left  = label1.Right + 6;  // <= this is what you need
    textBox1.Width = panel2.Width - label1.Width - 8;   // <= this is nice to have
}

Of course your offsets may vary..and obviously the Label has AutoSize = true

Edit

Since you commented on the problem of getting the TextBoxes aligned with each other across rows here are a few thoughts about this problem. As Hans noted, you can't have it all:

  • Complete freedom for the Labels' content
  • Perfect fits
  • And aligned Textboxes

The three goals conflict. So you need to make compromises:

  • If you can restrict the content to a fixed maximum, the result will look best
  • Sometimes it helps to have a collegue or even a user look at the content to find a shorter way to express the meaning
  • Ellipsis or abbreviations may help. I both cases you should set a ToolTip to show the full content
  • Another option is to switch to a narrower Font for some Labels
  • Instead of one fixed Label size maybe 2 or 3 will help: The look will be a bit jagged but will look a lot better than with completely free sizes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM