I have a few Labels and a bunch of TextBoxes that I want to dynamically add to a Panel. The TextBoxes are are added OK and are perfectly visible, but the Labels are not. Here is the code I'm using to add the Labels.
The language is C# written for .NET 3.5 WinForms application.
Label lblMotive = new Label();
lblMotive.Text = language.motive;
lblMotive.Location = new Point(0, 0);
Label lblDiagnosis = new Label();
lblDiagnosis.Text = language.diagnosis;
lblDiagnosis.Location = new Point(20, 0);
panelServiceMotive.Controls.Add(lblMotive);
panelServiceMotive.Controls.Add(lblDiagnosis);
panelServiceMotive is the Panel control that should display the Labels, as well as the earlier mentioned TextBoxes. language is an object of a self-written Language class which works OK and is irrelevant here.
I hope that's enough info to get help.
It looks like the the main problem is the location of the controls that you add to the panel. The Location
property holds the coordinates of the upper left edge of the control relative to the upper left corner of the parent control (the control in which you add child controls). Looking at your code, it appears that you add controls one on top of the other. Note that you always set lblDiagnosis.Location = new Point(0, 0);
. If you add controls from code, the first control that you add will cover all the other controls that you add at the same location (unlike when using designer).
You could try something like this to check if the labels are ok:
Label lblMotive = new Label();
lblMotive.Text = language.motive;
lblMotive.Location = new Point(0, 40);
Label lblDiagnosis = new Label();
lblDiagnosis.Text = language.diagnosis;
lblDiagnosis.Location = new Point(0, lblMotive.Location.Y + lblMotive.Size.Height + 10);
panelServiceMotive.Controls.Add(lblMotive);
panelServiceMotive.Controls.Add(lblDiagnosis);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With