Jonas Stawski

Everything .NET and More

Assigning Text to the Password Textbox

For security reasons setting the text property of a TextBox of type passwords does absolutely nothing. Go ahead, give it a try. Add a TextBox to an ASP.NET page:

<asp:TextBox ID="tbPassword" runat="server" TextMode="Password" MaxLength="15" />

and on the code behind do this:

tbPassword.Text = "HelloWorld";

You will notice that when the page loads, the TextBox is empty. There are some cases where you really need to assign it. For example, I have a new user form with AJAX in it and every time I generate an asynch postback i loose the password text. Although the user never saw a postback. To solve the problem I assign the text in the following manner:

tbPassword.Attributes["value"] = Request.Form[tbPassword.ClientID.Replace("_", "$")];

Since I'm using Master Pages the Client ID of the TextBox is changed by ASP.NET and therefore so is it's Name. The good news is that the Name of the TextBox is the same as the ClientID but instead of using "_", it uses "$". Hence the replace code.

Happy Programming!

Add comment