Reputation: 371
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
Upvotes: 0
Views: 2013
Reputation: 5373
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.
Upvotes: 1
Reputation: 1567
I'm afraid not, you would have to use either UserControl
or CustomControl
as there is no way to add a TextBox
and associated Label
at the same time
Upvotes: 0