Lets say I have a text box which should have a default value…. and it is in an initializing function like so:
void InitializeControls()
{
myTextBox.Text = "Default Text";
}
Now, lets say that I have a button, which does a postback… I want to save the user entered value of the textbox off somewhere in the button’s OnClick event.
My question is, when should I call the initializing control code above? I’m thinking it should be in the OnLoad function, however this seems like that I will overwrite the postback data everytime:
protected override void OnLoad(EventArgs eventArgs)
{
base.OnLoad(eventArgs);
InitializeControls();
}
Will the postback data overwrite my default text above if I have the initializing code in the OnLoad?
Thanks
Call
InitializeControls()in theOnInit, before the call tobase.OnInit(). In this way your default value will not be part of the ViewState and you will not be passing it to the client and back for no reason.You could also just set the default value in the mark-up (in the .aspx file).
Do not call InitializeControls() in PageLoad / OnLoad since this will add the default value to ViewState, bloating ViewState for no reason.
Read the article TRULY understanding ViewState to get a good understanding of this stuff.