开发者

ViewState["sample"] Variable not retaining value on postback in a composite control

I have created a composite control with sample details as follows. Basically, the first time on page load the control sets a view state variable and the problem is that on post back (when the button is clicked), the ViewState variable is null. I have researched extensively and I am not able to find a solution. I checked all the Microsoft recommended articles and also from ot开发者_JAVA百科her developers. This approach seem to work for everyone and I can't figure out what I'm doing wrong. If anyone can help, I would really appreciate it.

PS: This code may not work as it is only for illustrative purposes. but this is exactly what i'm doing in my code.

Public class Test : CompositeControl
{
    private Button btnTest = new Button();
    public string TestViewState
    {
        get
        {
            string s = (string)ViewState["test"];
            return (s == null) ? String.Empty : s;
        }
        set
        {
            ViewState["test"] = value;
        }
    }

    private void set()
    {
        TestViewState = "test";
    }

    protected void Page_Load(object sender, EventArgs e)
    {  
        if(!Page.IsPostBack)
            set();  
    }

    protected override void RecreateChildControls()
    {
        EnsureChildControls();
    }

    protected override void CreateChildControls()
    {
         base.Controls.Clear();  
         btnTest.ID = "btnTest";
         btnTest.Click += new EventHandler(btnSubmitTest_Click);

         if (!ChildControlsCreated)
         Controls.Add(btnTest);      

        base.CreateChildControls();
    }

    protected override void Render(HtmlTextWriter writer)
    {
        btnSumbit.Render(writer);
    }

    protected void btnSubmitTest_Click(object sender, EventArgs e)
    {
        string test = TestViewState; // Viewstate value is null here!!!!!!
    }
}


Are you sure that Page_Load is getting called? As far as I can remember that "notation" works only on pages and User Controls (didn't check that). Try overriding:

protected override void OnLoad(EventArgs e)
{
    ...
}

Test it with a Debugger.


Ok, the enableviewstate was disabled at the web.config level by another team member. Glad I found it. Thanks Arthur for confirming it worked for you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜