Password Mask an unbound TextBox column in a DataGridView (VB.NET)

If you have ever wanted to mask the contents in a TextBox column on a DataGridView (DGV) control, you will notice that there is no pre-defined “password” format that you can apply.  I have gotten around this by setting the DataPropertyName attribute of the column and then checking the related property in the CellFormatting event.  It’s actually pretty simple and doesn’t involve very much coding at all!

DataPropertyName = "password"

DataPropertyName = "password"

After you have set the DataPropertyName for the related column(s) in your DGV, you need to add code that will evaluate this property when the data is loaded.  For this, I will use the CellFormatting event.

Before we begin, I want to set the character that will be displayed instead of actual value.  For this, I will use an asterisk (*).

Private pwd As Char = “*”

In the below example, my DataGridView is named dg_Divisions.  This routine will store the value of any field with the DataPropertyName of “password” into the related cell’s Tag property and will change each character in the Value to an asterisk.  If the field is not a “password” field, it will set the Tag to Nothing (null).

Private Sub dgv_PwdFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles dg_Divisions.CellFormatting
If dg_Divisions.Columns(e.ColumnIndex).DataPropertyName = “passwordAnd e.Value <> Nothing Then
dg_Divisions.Rows(e.RowIndex).Tag = e.Value
e.Value = New String(pwd, e.Value.ToString.Length)
Else
dg_Divisions.Rows(e.RowIndex).Tag = Nothing
End If
End Sub
After the Tags and Values have been changed, we want the user to be able to see and modify the value if they begin editing the cell.  To do this, I will use the EditingControlShowing event.
Private Sub dgv_PwdEditing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) Handles dg_Divisions.EditingControlShowing
If (dg_Divisions.CurrentRow.Tag <> Nothing) Then
e.Control.Text = dg_Divisions.CurrentRow.Tag.ToString()
End If
End Sub
Value displayed as asterisks

Value displayed as asterisks

Editing the cell displays the underlying contents

Editing the cell displays the underlying contents

That’s all there is to it!  Happy coding!