【发布时间】:2016-10-11 18:31:51
【问题描述】:
使用 C#,我使用 Windows 窗体拖放了一个按钮,并动态创建了一个按钮和文本框。我想在按钮上显示来自文本框的输入。硬编码按钮工作正常,但动态按钮使程序崩溃,并出现 System.NullReferenceException。
请帮助我了解如何通过单击动态创建的按钮从动态创建的文本框中获取输入。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
Button btnDynamic;
TextBox txtBoxYear;
public Form1()
{
InitializeComponent();
tp();
}
private void Form1_Load(object sender, EventArgs e)
{
Button btn = (Button)sender;
btnHardCode.Text = txtBoxYear.Text; //This hard coded button works
// btnDynamic.Text = txtBoxYear.Text; //The dynamic button crashes the program with a
//System.NullReferenceException
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void tp() //put textbox and button on tab on tab click
{
var tab = tabControl1.TabPages[0];
//tab.Controls.Clear();
var btnDynamic = new Button()
{
Size = new Size(75, 30),
Left = 40,
Top = 50,
Text = "try",
};
btnDynamic.Click += new EventHandler(this.Form1_Load);
tab.Controls.Add(btnDynamic);
txtBoxYear = new TextBox()
{
Size = new Size(200, 100),
Left = 20,
Top = 10,
};
tab.Controls.Add(txtBoxYear);
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
【问题讨论】: