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);
        }
    }
Omu
  • 69,856
  • 92
  • 277
  • 407
  • Did you make sure the control is added early enough (i.e. in Page_Init) to the State bag? – Olaf Aug 08 '11 at 09:11
  • @Olaf it's added in the markup – Omu Aug 08 '11 at 09: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. – Olaf Aug 08 '11 at 09: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. – Olaf Aug 08 '11 at 09:51

1 Answers1

1

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

Alex
  • 180
  • 4