title: How to correctly override the TextBox.Text property
body: <p>In <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="nofollow">Windows Forms</a> and C#, I am inheriting from the TextBox class. I override the Text property from TextBox. Everything goes well until I try to use the TextChanged event. The OnTextChanged event does not work properly here, as the Text.set property is not invoked.</p>
  
  <pre><code>Initial field content 123, txpText.Text = 123
  Field content changed to a   , txpText.Text still 123
  Field content changed to aa  , txpText.Text still 123
  Field content changed to aaa , txpText.Text still 123
  </code></pre>
  
  <p>Here is my custom TextBox code</p>
  
  <pre><code>public class ShowPartialTextBox : System.Windows.Forms.TextBox
  {
      private string _realText;
      public override string Text
      {
          get { return _realText; }
          set // &lt;--- Not invoked when TextChanged
          {
              if (value != _realText)
              {
                  _realText = value;
                  base.Text = _maskPartial(_realText);
                  //I want to make this _maskPartial irrelevant
              }
          }
      }
  
      protected override void OnTextChanged(EventArgs e)
      {
          //Always called. Manually invoke Text.set here? How?
          base.OnTextChanged(e);
      }
  
      private string _maskPartial(string txt)
      {
          if (txt == null)
              return string.Empty;
          if (_passwordChar == default(char))
              return txt;
          if (txt.Length &lt;= _lengthShownLast)
              return txt;
          int idxlast = txt.Length - _lengthShownLast;
          string result = _lpad(_passwordChar, idxlast) + txt.Substring(idxlast);
          return result;
      }
  }
  </code></pre>
  
  <p>Here is the Form class</p>
  
  <pre><code>public partial class Form1 : Form
  {
      private ShowPartialTextBox txpText;
  
      private void InitializeComponent()
      {
          txpText = new ShowPartialTextBox();
          txpText.Text "123";
          txpText.TextChanged += new System.EventHandler(this.txpText_TextChanged);
      }
  
      private void txpText_TextChanged(object sender, EventArgs e)
      {
          label1.Text = txpText.Text; //always shows 123
      }
  }
  </code></pre>
  
  <p>I use _maskPartial. It is altering the displayed Text, while still preserving its real content. I want this custom TextBox to "almost" simulate PasswordChar property, with showing the last x characters.</p>