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
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.
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.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
//-- Create your controls here
}
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 =...;
}