Dynamically created controls causing Null reference

I am trying to dynamically create controls and give them properties during run time.

I have put my code inside the Page_Init event, when I run my website I can see my controls but when I click on the submit button an error occurrs saying “Object reference not set to an instance of an object”.

Here is the code I have used:

    //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);

How can I fix this error?

This Is the Stack Trace

[NullReferenceException: Object reference not set to an instance of an object.]
_Default.Page_PreInit(Object sender, EventArgs e) in c:UsersbilalqDocumentsVisual Studio 2010WebSitesWebSite3Default.aspx.cs:31
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(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +328

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

As FindControl is not recursive, you have to replace this code :

Label FeedbackLabel = (Label)FindControl("FeedbackLabel");
TextBox InputTextBox = (TextBox)FindControl("InputTextBox");

by this code :

Label FeedbackLabel = (Label)Panel1.FindControl("FeedbackLabel");
TextBox InputTextBox = (TextBox)Panel1.FindControl("InputTextBox");

However, according other answers, you should move the declaration (not the instantiation) outside the method (at class level) in order to easily get an entry for your controls.

Method 2

try to put your code in the Page_Load instead of Page_Init and also, check for null before using objects returned by FindControl.

I suspect the object InputTextBox is null and it crashes when you try to print its Text.

as a general rule just check for null and also for type when casting results of FindControl to something else.

Method 3

The FindControl is failing because it can’t find the control and causing a null reference.

Just reference it directly using FeedbackLabel as you already have it in your class. Just move the scope outside of your ‘Init’ method.

private Label feedbackLabel = new Label();
private TextBox inputTextBox = new TextBox();
private Button submitButton = new Button();

public void Page_Init(EventArgs e)
{
    feedbackLabel.ID = "FeedbackLabel";
}

protected void SubmitButton_Click(object sender, EventArgs e)
{
    feedbackLabel.Text =...;
}

Method 4

I suggest that you declare your controls outside the page_int and do your initialization in the init then use them with their name instead of find control.

Method 5

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        //-- Create your controls here
    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x