1

I am trying to recreate the TextBox control, the problem is that after the postback the value in the textbox returns to it's initial state.

Anybody knows how to make it persist the value after postbacks ?

    [DefaultProperty("Text")]
    [ToolboxData("<{0}:MyTextBox runat=server></{0}:MyTextBox>")]
    public class MyTextBox : WebControl
    {

        [Bindable(true)]
        [DefaultValue("")]
        public string Text
        {
            get
            {
                return (String)ViewState["Text"] ?? string.Empty;
            }

            set
            {
                ViewState["Text"] = value;
            }
        }


        protected override void RenderContents(HtmlTextWriter output)
        {
            var a = string.Format(@"<input type='text' id='{0}' name='{0}' value='{1}' />", ID, Text);

          output.Write(a);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            RenderContents(writer);
        }
    }
4
  • Did you make sure the control is added early enough (i.e. in Page_Init) to the State bag? Commented Aug 8, 2011 at 9:11
  • @Olaf it's added in the markup Commented Aug 8, 2011 at 9:12
  • 2
    Wouldn't it be an option to inherit from TextBox instead of WebControl (and override Text)? That's not a direct answer to your question, but might solve the underlying problem. Commented Aug 8, 2011 at 9:46
  • 2
    Alex is right: if you don't inherit from TextBox (which does this automatically) you have to read the posted value from Request.Form[this.ClientID] manually, for instance when "getting" the text. I've tried, it works. Commented Aug 8, 2011 at 9:51

1 Answer 1

1

Your input doesn't have a name... Without a name his value will never posted back!

Sign up to request clarification or add additional context in comments.

3 Comments

indeed, but apparently this is not enough
And you should check Request[this.Name] to update your Text, otherwise it will be always empty!
implementing IPostBackDataHandler also helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.