[英]Visual C#: How to add controls to a form created with code?
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. 我是Visual C#的新手,我目前仍停留在如何创建新表单(使用代码而非设计)以及如何向该新表单中添加内容(即标签和文本框)上。 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. 运行此代码时,我将获得默认表单,然后单击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.
我环顾了StackOverflow并提出了另一个主题,但是它的解决方案对我不起作用。 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 . 您正在内存中创建Label对象,但没有将其分配给特定的父控件,也没有设置其位置等。Google“动态创建控件C#”,您将找到大量示例 。
You basically need to call the following two lines from somewhere in profileForm. 基本上,您需要从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
这是视频: http : //windowsclient.net/learn/video.aspx?v=13245
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.