我正在尝试动态创建控件并在运行时为它们提供属性。
我已将代码放在 Page_Init 事件中,当我运行我的网站时,我可以看到我的控件,但是当我单击提交按钮时,会出现错误,提示“对象引用未设置为对象的实例”。
这是我使用的代码:
//Creates instances of the Control
Label FeedbackLabel = new Label();
TextBox InputTextBox = new TextBox();
Button SubmitButton = new Button();
// Assign the control properties
FeedbackLabel.ID = "FeedbackLabel";
FeedbackLabel.Text = "Please type your name: ";
SubmitButton.ID = "SubmitButton";
SubmitButton.Text = "Submit";
InputTextBox.ID = "InputTextBox";
// Create event handlers
SubmitButton.Click += new System.EventHandler(SubmitButton_Click);
// Add the controls to a Panel
Panel1.Controls.Add(FeedbackLabel);
Panel1.Controls.Add(InputTextBox);
Panel1.Controls.Add(SubmitButton);
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
// Create an instance of Button for the existing control
Button SubmitButton = (Button)sender;
// Update the text on the Button
SubmitButton.Text = "Submit again!";
// Create the Label and TextBox controls
Label FeedbackLabel = (Label)FindControl("FeedbackLabel");
TextBox InputTextBox = (TextBox)FindControl("InputTextBox");
// Update the controls
FeedbackLabel.Text = string.Format("Hi, {0}", InputTextBox.Text);
我该如何解决这个错误?
这是堆栈跟踪
[NullReferenceException:对象引用未设置为对象的实例。] c:\Users\bilalq\Documents\Visual Studio 2010\WebSites\WebSite3\Default.aspx.cs:31 中的 _Default.Page_PreInit(Object sender, EventArgs e) System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35 System.Web.UI.Page。 OnPreInit(EventArgs e) +8876158 System.Web.UI.Page.PerformPreInit() +31 System.Web.UI.Page.ProcessRequestMain(布尔 includeStagesBeforeAsyncPoint,布尔 includeStagesAfterAsyncPoint) +328