联系动态创建的控件
我在运行时为我的 winform 应用程序创建了一个 textBox
控件。一旦表单加载,该控件就会出现,并且效果也很好。但是,我刚刚遇到了一个问题,因为我意识到我不知道如何编写代码来写入动态创建的控件。
假设我在设计时创建了一个按钮(名为“Button1”)。在 Button1 的单击事件 (Button1_Click
) 中,我想将单词“Hello”写入文本框控件,该控件在执行应用程序之前不会创建。下面是一些代码:
C# 代码:
// Create the textBox control
TextBox new_textBox = null;
int x = 10;
int y = 10;
int xWidth = 300;
int yHeight = 200;
new_textBox = new TextBox();
new_textBox.Text = controlText;
new_textBox.Name = "textBox" + controlName;
new_textBox.Size = new System.Drawing.Size(xWidth - 10, yHeight - 10);
new_textBox.Location = new Point(x, y);
new_textBox.BringToFront();
new_textBox.Multiline = true;
new_textBox.BorderStyle = BorderStyle.None;
// Add the textBox control to the form
this.Controls.Add(new_textBox);
问题:
从 Button1_Click
事件中,我无法联系尚未创建的控件。因此,Visual Studio 将抛出一个明显的错误,表明该控件不存在(因为它不存在)。
那么,有没有什么方法可以动态调用控件等等 具体来说,一个文本框控件?
感谢您对此事的任何帮助,
埃文
I have created a textBox
control on run-time for my winform application. The control appears just find once the form loads up, and works great too. However, I have just run into a problem as I realize I do not know how to write the code to write to a dynamically created control.
Let's assume I have created a button (named "Button1") on design time. In Button1's click event, (Button1_Click
), I would like to write the word "Hello" to a textBox control that won't be created until the application is executed. Some code below:
C# Code:
// Create the textBox control
TextBox new_textBox = null;
int x = 10;
int y = 10;
int xWidth = 300;
int yHeight = 200;
new_textBox = new TextBox();
new_textBox.Text = controlText;
new_textBox.Name = "textBox" + controlName;
new_textBox.Size = new System.Drawing.Size(xWidth - 10, yHeight - 10);
new_textBox.Location = new Point(x, y);
new_textBox.BringToFront();
new_textBox.Multiline = true;
new_textBox.BorderStyle = BorderStyle.None;
// Add the textBox control to the form
this.Controls.Add(new_textBox);
The Problem:
From Button1_Click
event, I cannot get in contact with a control that has not even been created yet. Thus, Visual Studio will throw an obvious error that the control does not exist (because it doesn't).
So, is there some way to dynamically call a control, and more
specifically, a textBox control?
Thank you for any help on the matter,
Evan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在类范围内声明
new_textBox
。然后编译器就可以访问它。例如:Declare the
new_textBox
at class scope. Then the compiler can access it. For example:您可以将
new_textBox
设为类成员(表单成员)。您可以再次为其分配一个值,并稍后动态添加到表单控件中。不过,检查 buttonClick 事件中是否为 null 是一个很好的做法。
You can make the
new_textBox
a class member (member of the form). You can again assign it a value and add to the forms controls later dynamically.It would be a good practice to check if is null in the buttonClick event, though.