,代码生成form有关问题
求助,代码生成form问题。
点击按钮button1用代码动态生成一个新窗体
代码:
Form fm1 = new Form();
fm1.StartPosition = FormStartPosition.CenterScreen;
fm1.Size = new System.Drawing.Size(400, 160);
fm1.Text = "测试";
然后生成一个button和一个textbox
代码:
Button button = new Button();
button.Name = "button";
button.Text = "登陆";
button.Location = new Point(10, 10);
button.Size = new Size(24, 57);
button.Click += button_Click;
TextBox tbd = new TextBox();
tbd.Name = "TextBox";
tbd.Text = "测试文本";
tbd.Location = new Point(50, 10);
tbd.Size = new Size(24, 57);
然后将按钮和文本框加入到fm1中
代码:
fm1.Controls.Add(tbd);
fm1.Controls.Add(button);
然后给按钮button添加一个事件button_Click
void button_Click(object sender, EventArgs e)
{
//这里如何访问文本框的text属性
}
我的问题是如何在这个事件中访问跟这个button一起生成的textbox的Text
如:
void button_Click(object sender, EventArgs e)
{
string str = tbd.Text;//这里不能访问tbd,请问是怎么回事
}
------解决思路----------------------
你把 button 和 textbox的声明放到窗体类外边就可以这样用了。
楼主真是初学者,为啥要把控件生成放到后台呢。
点击按钮button1用代码动态生成一个新窗体
代码:
Form fm1 = new Form();
fm1.StartPosition = FormStartPosition.CenterScreen;
fm1.Size = new System.Drawing.Size(400, 160);
fm1.Text = "测试";
然后生成一个button和一个textbox
代码:
Button button = new Button();
button.Name = "button";
button.Text = "登陆";
button.Location = new Point(10, 10);
button.Size = new Size(24, 57);
button.Click += button_Click;
TextBox tbd = new TextBox();
tbd.Name = "TextBox";
tbd.Text = "测试文本";
tbd.Location = new Point(50, 10);
tbd.Size = new Size(24, 57);
然后将按钮和文本框加入到fm1中
代码:
fm1.Controls.Add(tbd);
fm1.Controls.Add(button);
然后给按钮button添加一个事件button_Click
void button_Click(object sender, EventArgs e)
{
//这里如何访问文本框的text属性
}
我的问题是如何在这个事件中访问跟这个button一起生成的textbox的Text
如:
void button_Click(object sender, EventArgs e)
{
string str = tbd.Text;//这里不能访问tbd,请问是怎么回事
}
------解决思路----------------------
你把 button 和 textbox的声明放到窗体类外边就可以这样用了。
楼主真是初学者,为啥要把控件生成放到后台呢。