@ASP.NET Forums: How to set text to a Password TextBox?
My serie of all sorts of hacks continues... :-)
As per subject, it was asked at Forums how to set the text to a password mode TextBox such that you could populate it from database, for example. Point is that ASP.NET TextBox does not care about the Text property when it is in the Password mode. It just posts the value once but doesn't keep it over the postback by default. If you want to get the feature, understand that this changes it so that password will be carried along with postbacks. However, here you go.
The first option
Just add it to the Attributes collection of TextBox with "value" as key.
[C#]
TextBox1.Attributes["value"]="I'm set";
[VB]
TextBox1.Attributes("value")="I'm set"
The second option
You can also write this out as a custom control, which derives from TextBox and adds the proper logic to carry the value around. This way you could continue using the TextBox as you generally do via the Text property, no need to care about when adding attribute and when not.
[C#]
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Joteke.Controls
{
public class MyTextBox : TextBox
{
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender (writer);
if(this.TextMode == TextBoxMode.Password)
{
string text=this.Text;
if(text.Length > 0)
writer.AddAttribute(HtmlTextWriterAttribute.Value,text);
}
}
}
}
[VB] (translated from C# code)
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Namespace Joteke.Controls
Public Class MyTextBox
Inherits TextBox
Protected Overrides Sub AddAttributesToRender(writer As HtmlTextWriter)
MyBase.AddAttributesToRender(writer)
If Me.TextMode = TextBoxMode.Password Then
Dim [text] As String = Me.Text
If [text].Length > 0 Then
writer.AddAttribute(HtmlTextWriterAttribute.Value, [text])
End If
End If
End Sub 'AddAttributesToRender
End Class 'MyTextBox
End Namespace 'Joteke.Controls
EDIT - code for developing same with HtmlInputText (needs custom control)
public class MyHtmlInputText : System.Web.UI.HtmlControls.HtmlInputText
{
protected override void RenderAttributes(HtmlTextWriter writer)
{
string val=base.Attributes["value"] as string;
if(val != null)
{
writer.WriteAttribute("value",val,false);
}
base.RenderAttributes(writer);
}
}
Thanks