Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

c# - 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;
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...