I'm new to Visual C# and I'm currently stuck on how to create a new form (with code, not design) and add things (namely labels and textboxes) to this new form. Here's what I have right now:
namespace AccountInfo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
profileForm profile = new profileForm(); // Make new form
profile.Name = "newProfile";
profile.Text = "Add a new profile";
profile.LabelText = "test";
profile.Show(); // Display form
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
public class profileForm : Form
{
// Controls
Label label1 = new Label();
public profileForm()
{
}
public string LabelText
{
set { label1.Text = value; }
}
private void profileForm_Load(object sender, EventArgs e)
{
}
}
}
When I run this code, I get the default form and I click button1. It brings up a new form, but with nothing on it. I expect a label to show up but it won't. I've tried this multiple different ways (this being my most recent method) and I can't get anything to show up. I've looked around StackOverflow and one other topic came up, but its solution didn't work for me. I'd appreciate any insight into this :) Thanks a ton!
Edit: I've also tried this using the constructor instead. It didn't help.
You're creating a Label object in memory but you're not assigning it to a particular parent control, or setting it's position etc... Google "Dynamically create controls C#" and you'll find a tonne of examples .
You basically need to call the following two lines from somewhere in profileForm.
label1.Location = new Point(25,25);
this.Controls.Add(label1);
根据Dylan的建议,您需要在load事件中将Label对象添加到profileForm中,如下所示:
this.Controls.Add(label1);
Soon, i was watching a video that answers to this question. It is complete guide how to add dinamicly controlls with the flow layout. Here is the video: http://windowsclient.net/learn/video.aspx?v=13245
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.