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!
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.CellFormattingIf dg_Divisions.Columns(e.ColumnIndex).DataPropertyName = “password” And e.Value <> Nothing Thendg_Divisions.Rows(e.RowIndex).Tag = e.Valuee.Value = New String(pwd, e.Value.ToString.Length)Elsedg_Divisions.Rows(e.RowIndex).Tag = NothingEnd IfEnd Sub
Private Sub dgv_PwdEditing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) Handles dg_Divisions.EditingControlShowingIf (dg_Divisions.CurrentRow.Tag <> Nothing) Thene.Control.Text = dg_Divisions.CurrentRow.Tag.ToString()End IfEnd Sub
That’s all there is to it! Happy coding!