コントロールを動的に作成し、実行時にプロパティを指定しようとしています。
コードを Page_Init イベント内に配置しました。Web サイトを実行するとコントロールが表示されますが、送信ボタンをクリックすると、「オブジェクト参照がオブジェクトのインスタンスに設定されていません」というエラーが発生します。
これが私が使用したコードです:
//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(オブジェクト送信者、EventArgs e) System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp、オブジェクト o、オブジェクト t、EventArgs e) +14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(オブジェクト送信者、EventArgs e) +35 System.Web.UI.Page。 OnPreInit(EventArgs e) +8876158 System.Web.UI.Page.PerformPreInit() +31 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +328