Dynamically created controls causing Null reference

后端 未结 5 1602
情深已故
情深已故 2021-01-07 15:26

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 m

相关标签:
5条回答
  • 2021-01-07 15:55

    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.

    0 讨论(0)
  • 2021-01-07 15:56

    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.

    0 讨论(0)
  • 2021-01-07 15:57

    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.

    0 讨论(0)
  • 2021-01-07 16:03
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            //-- Create your controls here
        }
    
    0 讨论(0)
  • 2021-01-07 16:16

    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 =...;
    }
    
    0 讨论(0)
提交回复
热议问题