Take the 2-minute tour ×

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);
            i = i + 10;
share|improve this question
add comment

3 Answers

up vote 1 down vote accepted

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.

share|improve this answer
add comment
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.

share|improve this answer
add comment

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

share|improve this answer
ok then later on can we treat it like real text box like all its properties events etc etc –  Afnan Bashir Jan 18 '11 at 0:51
idk, he's never setting the .Name property to anything unique... –  jcolebrand Jan 18 '11 at 0:52
@Afnan: It is a real textbox. –  SLaks Jan 18 '11 at 0:54
Good point friend –  Afnan Bashir Jan 18 '11 at 0:54
@Drach: The Name doesn't matter. –  SLaks Jan 18 '11 at 0:54
show 3 more comments

Your Answer


