Reputation: 2905
This is a follow up to: ASP.Net: GridView control and combobox woes
I've implemented my code as kd7 has answered but I'm getting a "System.NullReferenceException: Object reference not set to an instance of an object." I've simplified the code as follows:
Event handler for the button click:
protected void btnSubmit_Click(object sender, EventArgs e)
{
ViewState["MyKey"] = "Test";
}
The Page_Load now has:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
txtDisplay.Text = ViewState["MyKey"].ToString();
}
}
My question is: Why is ViewState["MyKey"] coming back as null and causing a NullReference exception?
Please note that the code above is only a simplified version of what I'm trying to do. Please see the previous question given in the first line of this question to see full details.
Any suggestions?
Upvotes: 0
Views: 170
Reputation: 2256
The NullReferenceException might be related to the fact that you are trying to get the ViewState["MyKey"] value before you have set it. Try validating first:
if (ViewState["MyKey"] != null)
{
txtDisplay.Text = ViewState["MyKey"].ToString();
}
else
{
//manage the situation accordingly
}
Hope this helps!
Upvotes: 0
Reputation: 4467
Because in the asp page lifecycle the page load is called before the postback event is executed.
How about: -
protected void btnSubmit_Click(object sender, EventArgs e)
{
txtDisplay.Text = "Test";
}
Upvotes: 1