Initializing the contents of a password textfield in ASP.NET 2.0

Question
How do I initialize the contents of a password textfield in ASP.NET 2.0?

Simple anwser
You can’t! This doesn’t work (apparently this is for security reasons, although the exact motivation escapes me):

txtPassword.Text = "this sucks";

Better answer
Create an event handler for the TextBox’s PreRender event:

protected void txtPassword_PreRender(object sender, EventArgs e)
{
    TextBox txt = (TextBox)sender;
    txt.Attributes["value"] = txt.Text;
}

Voilá! Now you can assign to the Text property as in the first example.

(Credits for this tip to David Silverlight.)

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.