开发者

ASP.Net: GridView control and combobox woes part 2

This is a fo开发者_JAVA技巧llow 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?


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";
}


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜