How to keep the Text of a Read only TextBox after PostBack()?

前端 未结 7 1110
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 07:05

I have an ASP.NET TextBox and I want it to be ReadOnly. (The user modify it using another control)

But when there is a PostBack()

相关标签:
7条回答
  • 2020-12-08 07:41

    Here is a way to do it with javascript in the onfocus event of the Textbox itself.

    Doing it like this with javascript has the advantage that you don't need to do it in code behind, which can be difficult if you need to do it in gridviews or similar.

    This javascript code is only tested on Internet Explorer and certain parts of it will only work on IE, like for example the createTextRange part which is there just to make the caret end up at the beginning of the text in the Textbox, but that part can be skipped if not needed.

    If the core of this technique works on other browsers then it should be possible to make the code cross browser. The core of the idea here is the blur after setting readonly and then a timeout to set the focus again.

    If you only set readonly then it does not become readonly until next time you give the Textbox focus.

    And of course, the code can be put into a function instead which is called with "this" as argument.

      <asp:TextBox 
        ID="txtSomething" 
        runat="server"
        Text='<%# Bind("someData") %>'
        onfocus="
    var rng = this.createTextRange();
    rng.collapse();
    rng.select();
    if (this.allowFocusevent=='0') {return;};
    this.allowFocusevent='0';
    this.readOnly=true;
    this.blur();
    var that=this;
    setTimeout(function(){that.focus()},0);
    "
      />
    
    0 讨论(0)
  • 2020-12-08 07:43

    Get the value using Request.Form[txtDate.UniqueID]. You will get it !!

    0 讨论(0)
  • 2020-12-08 07:46

    Another solution I found and easier one:

    Add this to the Page Load method:

    protected void Page_Load(object sender, EventArgs e)
    {
         TextBox1.Attributes.Add("readonly", "readonly");
    }
    
    0 讨论(0)
  • 2020-12-08 07:57

    Have your other control store the value in a hidden field, and on postback, pull the value from the hidden field and push it into the textbox on the server side.

    0 讨论(0)
  • 2020-12-08 08:01

    Set the ContentEditable property of textbox to false ContentEditable="false".. It wont allow you to edit the contents of the textbox ie;will make the textbox readonly and also will make the value stay in the textbox after postback.. I think its the easiest way to do it..

    0 讨论(0)
  • 2020-12-08 08:08

    txtStartDate.Attributes.Add("readonly", "readonly"); on pageload in the best of the best solutions ,instead or Javascripts,hidden variables,cache,cookies,sessions & Caches.

    0 讨论(0)
提交回复
热议问题