简体   繁体   中英

Add label to textbox custom usercontrol in WinForm

I am writing a windows forms application that has a lot of textboxes. I want to add a label or a caption to the textbox, so that I don't have to drag a lot labels onto the form and deal with positioning etc. So far I have found 2 possible ways to do this.

  1. Create a user control with the label and textbox. How do I get the control, label and textbox to size appropriately depending on the text entered since the control will be reusable and different text sizes will be entered. How to get all the properties and events of the textbox to remain the same.

  2. Extend a normal textbox and add a string property called label or caption, and show this property at the left of the textbox. I know this can be done in Web.UI with CSS but is it possible in a winform and how?

Any suggestions on how to do either of these? Thanks.

You can create a UserControl that contains a label and a textbox. When you add the user control to your form, both the label and the textbox within will be added simultaneously. You can expose properties of the label and textbox to assign values at design or run time.

Using this method, you can add multiples of the user control to standardize the layout. As far as resizing the controls based on the text, you'll have to subscribe to events and change the sizing manually.

For example, you can subscribe to the TextChanged event of the label and the textbox. When the event fires, you calculate the size of the string and then adjust the width and position of the controls accordingly.

If you get to the point where you have too many textboxes, I would suggest switching to a DataGridView . The GridView component is very well suited for what you're describing, but of course it requires you to accept a grid layout.

One of the bonuses involved in using a GridView is hard to appreciate until you see it in action: it creates only one HWINDOW at a time (two if you're in editing mode). If you create Labels and TextBoxes all over your form, each one is registered with the operating system as an HWINDOW object. All those HWINDOW objects take time to display! In .NET 1.0, WinForms was so slow that dialogs with more than about two dozen controls were unusable. Even though .NET 2.0 is much better in this regard, but you'll still get significantly better performance by using a single control that manages lots of data, as opposed to lots of controls that each manage one piece of data.

Oh, and another option, if you like: you can also try a PropertyGrid . It has the advantage that it will also show help and allow you to create complex editing controls for each element.

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