Friday, 17 February 2012

Change ASP.NET Texbox as Password Texbox as Password


Introduction

Using ASP.NET, the default textbox in password mode (TextMode="Password") has the following restrictions:
  • The password can not be set (e.g., tbPassword.Text = "123";)
  • The password is not restored after a postback
Both restrictions make perfect sense for security reasons. Nonetheless, sometimes the above behaviour is not wanted (especially during development).
The new PasswordTextBox control is an extension of the standard ASP.NET TextBox and makes a password textbox behave like a regular textbox.

Using the code

The code itself is pretty straightforward:
    public class PasswordTextBox : TextBox
    {
        public PasswordTextBox()
        {
            TextMode = TextBoxMode.Password;
        }

        public override string Text
        {
            get
            {
                return base.Text;
            }
            set
            {
                base.Text = value;

                Attributes["value"] = value;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            Attributes["value"] = Text;
        }
    }
To use the code, just drop PasswordTextBox.dll in the /bin of your web application, or add a reference to it in Visual Studio.
ASP.NET 2.0 offers a nice and clean way to register controls for your aspx pages: you simply add the following to your web.config:
    <pages>
        <controls>
            <add tagPrefix="opp" assembly="PasswordTextBox" namespace="opp"/>
        </controls>
    </pages>
Now, you can use the PasswordTextBox as follows:
<opp:PasswordTextBox id="tbPassword" runat="server" />


Reference:
http://www.codeproject.com/KB/custom-controls/ASPNET_Password_TextBox.aspx

No comments:

Post a Comment