Click here to Skip to main content
15,899,754 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I want to add it based on a conditional statement

What I have tried:

flowLayoutPanel1.Controls.Add(control name);
Posted
Updated 16-Apr-17 0:43am
v2

Hi,

you must first create the control programmatically.
Example:
C#
var txt = new TextBox();
txt.name = "myNewTextBox";


Then you can add it to your flowLayoutPanel:

C#
flowLayoutPanel1.Controls.Add(txt);


Note: you cannot then refer to that TextBox in your code with this.myNewTextBox. You need to either save a reference to it (global variable or global dictionary?) or get its reference from flowLayoutPanel1.Controls. You may also need to handle the names of the textboxes: if you add two textboxes to your flowLayoutPanel with the same name, WinForm will assign the last added one a different name ("myNewTextBox1" ?).
Example:
C#
flowLayoutPanel1.Controls["myNewTextBox"].Text = "Hi!";


Handle Elements added to FlowLayoutPanel
As previously stated, you need to manage the name of textboxes (for instance, by using a counter) and then retrieve the TextBoxes in code knowing either the name or their index in the FlowLayoutPanel.Controls array.

Examples:
C#
//I have 10 textboxes in my flowlayoutpanel and want to access the third one:
var txt3 = myFlowLayoutPanel.Controls[2];

//I want to refer to the textbox named "mySpecialTextBox"
var txtSpecial = myFlowLayoutPanel.Controls["mySpecialTextBox"]



Side note: when in doubt, consult MSDN. In this particular case go here.
Hope this helps.

LG
 
Share this answer
 
v2
Thank you so much. It helped me alot. The only problem i have it now is how to set the properties of the newly added control
 
Share this answer
 
How do i identify each of the controls added to the flowControlPanel
 
Share this answer
 
Comments
LLLLGGGG 16-Apr-17 15:45pm    
You need to handle textboxes name property (or the order of insertion in the flowLayoutPanel) and then refer to my improved answer. If you want to manage the properties of the newly added controls you may eitehr set your preferred properties in code before adding them to the flowlayoutpanel (see my first example where I set the name property: you can set whatever property you need there) or get the reference to that control in the FlowLayoutPanel.Controls collection with the methods previously described.

Note: for the next times, do NOT use answers to ask some more clarifications. Instead, use comments! ;-)
MunsuleMPI 16-Apr-17 20:53pm    
Thanks. It is helpful

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900