﻿Imports System.ComponentModel

Public Class DataGridViewPasswordTextBoxColumn
    Inherits DataGridViewColumn

    Private _passwordChar As Char
    Private _useSystemPasswordChar As Boolean

    <Category("Password")>
    Public Property PasswordChar As Char
        Get
            Return _passwordChar
        End Get
        Set
            If _passwordChar <> Value Then
                _passwordChar = Value

                Dim cell = TryCast(CellTemplate, DataGridViewPasswordTextBoxCell)

                If cell IsNot Nothing Then
                    'Update the template cell.
                    cell.PasswordChar = Value
                End If

                If DataGridView IsNot Nothing Then
                    'Update each existing cell in the column.
                    For Each row As DataGridViewRow In DataGridView.Rows
                        cell = TryCast(row.Cells(Index), DataGridViewPasswordTextBoxCell)

                        If cell IsNot Nothing Then
                            cell.PasswordChar = Value
                        End If
                    Next

                    'Force a repaint so the grid reflects the current property value.
                    DataGridView.Refresh()
                End If
            End If
        End Set
    End Property

    <Category("Password")>
    Public Property UseSystemPasswordChar As Boolean
        Get
            Return _useSystemPasswordChar
        End Get
        Set
            If _useSystemPasswordChar <> Value Then
                _useSystemPasswordChar = Value

                Dim cell = TryCast(CellTemplate, DataGridViewPasswordTextBoxCell)

                If cell IsNot Nothing Then
                    'Update the template cell.
                    cell.UseSystemPasswordChar = Value
                End If

                If DataGridView IsNot Nothing Then
                    'Update each existing cell in the column.
                    For Each row As DataGridViewRow In DataGridView.Rows
                        cell = TryCast(row.Cells(Index), DataGridViewPasswordTextBoxCell)

                        If cell IsNot Nothing Then
                            cell.UseSystemPasswordChar = Value
                        End If
                    Next

                    'Force a repaint so the grid reflects the current property value.
                    DataGridView.Refresh()
                End If
            End If
        End Set
    End Property

    Public Sub New()
        MyBase.New(New DataGridViewPasswordTextBoxCell)
    End Sub

    Public Overrides Function Clone() As Object
        Dim copy = DirectCast(MyBase.Clone(), DataGridViewPasswordTextBoxColumn)

        copy.PasswordChar = _passwordChar
        copy.UseSystemPasswordChar = _useSystemPasswordChar

        Return copy
    End Function

End Class