简体   繁体   中英

How to add link Labels at run time in Windows form

I have been making a Windows Form Application in C# using the Visual C# 2008 IDE.
There are basically two forms in my application. One is created at Runtime and it's layout is undefined and the second one's predefined.
Now, I have been adding form elements using the toolbox provided and don't have any idea how to add them using written code(not using toolbox). I want to add n number of Labels to the second form which is undefined. n can be anything(decided at runtime, depending on the user's input). Can anybody tell me what is the efficient way to do this?

Just a quick example of a "dynamic control" being created at run-time and added to the form:

Label lbl = new Label();
lbl.Text = "Hello World!";
lbl.Location = new Point(100, 25);
this.Controls.Add(lbl);

You can replace "this" with the container to add it to, like "panel1" for instance. For containers that have their own layout engine, like a FlowLayoutPanel, then you wouldn't need to specify a Location().

Create a new LinkLabel() , set its properties (in particular, text and position), then add it to the Controls collection of your form or any panel.

You may also want to add event handlers, and store them somewhere (probably in a List<T> ) so you can change or remove them later.

Create one in the designer, configure it's properties as you wish. Then go to the designer file, which name is like Form1.Desiner.cs , copy the code related to your LinkLabel (find everything with text search) and paste it where you wish :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM