开发者

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;
        }


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜