Friday, March 16, 2012

Password Field not getting populated from Database

I have a web form password field that needs to show the password value as "****" from tha database. It seems that it all it shows is blank but when I change it to a regular text fiels it works. All I do is change the "TEXTMODE" property nothing more.

Any HelpHi,

ASP.NET TexBox just doesn't write out the text when it is in password mode, it's just security precaution. However if you absolutely need such feature, you can wrap it simply in a custom control.

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# with a tool)


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


I don't mind that security feature the only problem is that when you go to update a user the password field is blank and if you made no change to the password field then it updates as "" instead of the previous value.

Any solution for this then ?
Well, the password is in the HTML after postback (rendered along with the HTML), that's the only part.

As I said, previous control allows you to prepopulate TextBox even in password mode.
FYI: I blogged this one here.

http://blogs.aspadvice.com/joteke/archive/2005/02/03/2531.aspx

There's also provided the shortcut solution, that is just adding the value to the Attributes collection when you wouldn't need to write a custom control.

0 comments:

Post a Comment