简体   繁体   中英

Add Label with Textbox at design time

I am creating a project using VS.NET (C#) with many forms that contain textboxes and associated labels. I have created the association through an exposed property I created for the textbox which contains the label name. The problem is that each time I add a textbox at design-time I have to add a label and then enter the label name into the property of the textbox. I would much rather do this dynamically at design-time when I create the textbox, much like the old VB textbox add. I have been scouring the net for a way to dynamically add a label whenever I add a textbox at design-time without finding any acceptable solutions. I found an answer on this site that suggested adding a user control containing a textbox and label, and though it is probably the best solution I have found, I think it restricts me more than I would like. Do I have to go through some full-blown custom designer to do this hopefully simple task?

TIA

Although I like the solution that uses UserControl better (simpler and easier to handle), but there may be some cases where not creating one more thing that will eat the resources is preferable (for example if you need a lot of such label-textbox pairs on one form).

The simplest solution I came up with is as follows (the label shows in the designer after you build the project):

public class CustomTextBox : TextBox
    {
        public Label AssociatedLabel { get; set; }

        public CustomTextBox():base()
        {
            this.ParentChanged += new EventHandler(CustomTextBox_ParentChanged);
        }

        void CustomTextBox_ParentChanged(object sender, EventArgs e)
        {
            this.AutoAddAssociatedLabel();
        }

        private void AutoAddAssociatedLabel()
        {
            if (this.Parent == null) return;

            AssociatedLabel = new Label();
            AssociatedLabel.Text = "Associated Label";
            AssociatedLabel.Padding = new System.Windows.Forms.Padding(3);

            Size s = TextRenderer.MeasureText(AssociatedLabel.Text, AssociatedLabel.Font);
            AssociatedLabel.Location = new Point(this.Location.X - s.Width - AssociatedLabel.Padding.Right, this.Location.Y);

            this.Parent.Controls.Add(AssociatedLabel);
        }
    }

Although it isn't a complete solution, you need to code the additional behaviour such as moving the label with the textbox, changing the location of the label when its text changes, removing the label when the textbox is removed, and so on.

Another solution would be to not use the label at all, and just draw the text beside the textbox manually.

恐怕不是,您将不得不使用UserControlCustomControl因为无法同时添加TextBox和关联的Label

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