Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create controls dynamically

I want to know if this is possible in c# winform.

create control when ever button is pressed and place it at given location.

I think it is possible like this

private TextBox txtBox = new TextBox();
private Button btnAdd = new Button();
private ListBox lstBox = new ListBox();
private CheckBox chkBox = new CheckBox();
private Label lblCount = new Label();

but the problem lies when ever button is pressed same name controls are created.How to avoid that

What da........ i wrote and no exception i was expecting it because control already contains btnAdd instead as many button create as many you want. Accessing them will be issue but it will be solved by @drachenstern method correct?

  private void button1_Click_1(object sender, EventArgs e)
        {
            Button btnAdd = new Button();

            btnAdd.BackColor = Color.Gray;
            btnAdd.Text = "Add";
            btnAdd.Location = new System.Drawing.Point(90, 25+i);
            btnAdd.Size = new System.Drawing.Size(50, 25);
            this.Controls.Add(btnAdd);
            i = i + 10;
        }
like image 393
Afnan Bashir Avatar asked Jan 18 '11 00:01

Afnan Bashir


People also ask

How to create dynamic controls in c#?

Step 1: Create new windows form application. Step 2: Create win from like below. In code in button click event we create textbox control dynamically and add it to form's Control collection. Also we set location property of textbox.

Which event is used to generate controls dynamically?

Retaining the dynamic controls on PostBack In order to retain the dynamic TextBoxes across PostBacks, we need to make use of Page's PreInit event to recreate the dynamic TextBoxes using the Request.

What are dynamic controls?

Dynamic control is a method to use model predictions to plan an optimized future trajectory for time-varying systems. It is often referred to as Model Predictive Control (MPC) or Dynamic Optimization.


3 Answers

You could try the solution I posted here. It will dynamically create 5 buttons in the constructor. Just move the code to the button click event and it should add the buttons dynamically and register with the Click events.

like image 123
SwDevMan81 Avatar answered Sep 29 '22 10:09

SwDevMan81


int currentNamingNumber = 0;

txtBox.Name = "txtBox" + currentNamingNumber++;

Rinse, Repeat.

Gives each element a unique numeric name, allows you to find out how many elements have been created (notice that you don't want to decrement to track all created objects, because then you may create two elements with the same name).

I don't think you can pass the name you want into the new function, but you can always set the name after creating it.

like image 32
jcolebrand Avatar answered Sep 29 '22 10:09

jcolebrand


It sounds like your looking for a List<TextBox>.

like image 23
SLaks Avatar answered Sep 29 '22 09:09

SLaks