In this article I will explain with an example, how to keep (retain)
Password TextBox and prevent it from clearing across
PostBack in
ASP.Net using C# and VB.Net.
This article will explain, why
ViewState does not work for Password
TextBox i.e.
TextMode Password and why
Password TextBox clears on
PostBack in
ASP.Net using C# and VB.Net.
Security Reason
Retaining Password in
ASP.Net Password TextBox will make browsers print the
Password in the Page’s
HTML and hence it is not recommended to use this technique for
Login form.
Why ViewState does not work for ASP.Net Password TextBox?
ASP.Net does not store
Password TextBox values in ViewState due to the security reason and hence whenever
PostBack occurs, the values of
TextBoxes with
TextMode property set as
Password are not set.
If you try to set the Text property of the
Password TextBox, then too it will not be displayed in the Password
TextBox.
Though it is not recommended to retain values of Password TextBoxes across PostBack on Login forms, still there are places where it could be really helpful such as Registration Form where users need to enter Password twice.
HTML Markup
The
HTML Markup consists of following controls:
TextBox – For capturing UserName and Password.
Button – For submitting the Form.
The Button has been assigned with an OnClick event handler.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Username:</td>
<td><asp:TextBox ID="txtUserName" runat="server" /></td>
</tr>
<tr>
<td>Password:</td>
<td><asp:TextBox ID="txtPassword" runat="server" TextMode="Password" /></td>
</tr>
<tr>
<td><asp:Button ID="btnSubmit" Text="Submit" runat="server" /></td>
</tr>
</table>
Setting value of Password TextBox using C# and VB.Net
Inside the
Page Load event, the value of the
Password TextBox is set using the
HTML value attribute inside the
IsPostBack condition.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
txtPassword.Attributes["value"] = txtPassword.Text;
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Me.IsPostBack Then
txtPassword.Attributes("value") = txtPassword.Text
End If
End Sub
Screenshot
Demo
Downloads