DataGridView密码列

发布时间:2024年01月04日

想用DataGridView来显示密码,但又不要那么容易就显示出来,只有选中该密码列的单元格时才显示密码,不选中时则不显示,搜索一圈,发现都是采用EditingControlShowing、CellFormatting的,而且那些办法完全没有意义,因为那样处理后,你已经丢失了原有的密码信息,CellFormatting也相当耗资源

搜索到这个回答十分中肯:“可能你有特殊的需求,但是,一般情况下,不显示密码,因为没意义,显示是给人看的,但又想显示成****或其他什么的。我们一般不显示这一列。

本也想参考微软官网一些自定义DataGridView控件,写一个,能力不够,写不出来。

于是想,可以设置1列隐藏列(不显示)用来保存密码信息,一列显示列,用来在需要时显示密码。效果如下(实际中,将隐藏的密码列的Visible =False):

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DataGridView1.Columns.Add("列0", "列0")
        DataGridView1.Columns.Add("列1", "列1")
        DataGridView1.Columns.Add("密码", "密码")
        DataGridView1.Columns.Add("隐藏的密码", "隐藏的密码")
        DataGridView1.Columns("").Visible = False
    End Sub

    Dim CellLeaveRowIndex As Integer
    Private Sub DataGridView1_CellLeave(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellLeave
        CellLeaveRowIndex = e.RowIndex
        If e.ColumnIndex = DataGridView1.Columns("密码").Index Then
            DataGridView1.CurrentCell.Value = "*"
        End If
    End Sub

    Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged
        '当离开了正在编辑的行,跳到另一行时,取消之前行的编辑状态
        If CellLeaveRowIndex <> DataGridView1.CurrentCell.RowIndex Then
            DataGridView1.Rows(CellLeaveRowIndex).ReadOnly = True
        End If
    End Sub

    Private Sub AddBtn_Click(sender As Object, e As EventArgs) Handles AddBtn.Click
        DataGridView1.Rows.Add()
        DataGridView1.CurrentCell = DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(0)
        DataGridView1.CurrentRow.ReadOnly = False
    End Sub

    Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
        If e.ColumnIndex = DataGridView1.Columns("密码").Index Then
            DataGridView1.Rows(e.RowIndex).Cells("隐藏的密码").Value = DataGridView1.CurrentCell.Value
            DataGridView1.CurrentCell.Value = "*"
        End If
    End Sub

    Private Sub DataGridView1_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEnter
        If e.ColumnIndex = DataGridView1.Columns("密码").Index Then
            DataGridView1.CurrentCell.Value = DataGridView1.Rows(e.RowIndex).Cells("隐藏的密码").Value
        End If
    End Sub

    Private Sub DataGridView1_Leave(sender As Object, e As EventArgs) Handles DataGridView1.Leave
        '在此取消当前行的编辑状态
        DataGridView1.CurrentRow.ReadOnly = True
    End Sub

    Private Sub EditBtn_Click(sender As Object, e As EventArgs) Handles EditBtn.Click
        DataGridView1.CurrentRow.ReadOnly = False
    End Sub

End Class

文章来源:https://blog.csdn.net/zslefour/article/details/135381343
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。