Dynamically created controls causing Null reference

别等时光非礼了梦想. 提交于 2019-12-01 02:24:13

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.

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.

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.

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 =...;
}
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        //-- Create your controls here
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!