想用DataGridView来显示密码,但又不要那么容易就显示出来,只有选中该密码列的单元格时才显示密码,不选中时则不显示,搜索一圈,发现都是采用EditingControlShowing、CellFormatting的,而且那些办法完全没有意义,因为那样处理后,你已经丢失了原有的密码信息,CellFormatting也相当耗资源。
搜索到这个回答十分中肯:“可能你有特殊的需求,但是,一般情况下,不显示密码,因为没意义,显示是给人看的,但又想显示成****或其他什么的。我们一般不显示这一列。”
本也想参考微软官网一些自定义DataGridView控件,写一个,能力不够,写不出来。
于是想,可以设置1列隐藏列(不显示)用来保存密码信息,一列显示列,用来在需要时显示密码。效果如下(实际中,将隐藏的密码列的Visible =False):
Public Class Form1Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.LoadDataGridView1.Columns.Add("列0", "列0")DataGridView1.Columns.Add("列1", "列1")DataGridView1.Columns.Add("密码", "密码")DataGridView1.Columns.Add("隐藏的密码", "隐藏的密码")DataGridView1.Columns("").Visible = FalseEnd SubDim CellLeaveRowIndex As IntegerPrivate Sub DataGridView1_CellLeave(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellLeaveCellLeaveRowIndex = e.RowIndexIf e.ColumnIndex = DataGridView1.Columns("密码").Index ThenDataGridView1.CurrentCell.Value = "*"End IfEnd SubPrivate Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged'当离开了正在编辑的行,跳到另一行时,取消之前行的编辑状态If CellLeaveRowIndex <> DataGridView1.CurrentCell.RowIndex ThenDataGridView1.Rows(CellLeaveRowIndex).ReadOnly = TrueEnd IfEnd SubPrivate Sub AddBtn_Click(sender As Object, e As EventArgs) Handles AddBtn.ClickDataGridView1.Rows.Add()DataGridView1.CurrentCell = DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(0)DataGridView1.CurrentRow.ReadOnly = FalseEnd SubPrivate Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEditIf e.ColumnIndex = DataGridView1.Columns("密码").Index ThenDataGridView1.Rows(e.RowIndex).Cells("隐藏的密码").Value = DataGridView1.CurrentCell.ValueDataGridView1.CurrentCell.Value = "*"End IfEnd SubPrivate Sub DataGridView1_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEnterIf e.ColumnIndex = DataGridView1.Columns("密码").Index ThenDataGridView1.CurrentCell.Value = DataGridView1.Rows(e.RowIndex).Cells("隐藏的密码").ValueEnd IfEnd SubPrivate Sub DataGridView1_Leave(sender As Object, e As EventArgs) Handles DataGridView1.Leave'在此取消当前行的编辑状态DataGridView1.CurrentRow.ReadOnly = TrueEnd SubPrivate Sub EditBtn_Click(sender As Object, e As EventArgs) Handles EditBtn.ClickDataGridView1.CurrentRow.ReadOnly = FalseEnd SubEnd Class
DataGridView事件触发时间顺序:CellEnter-->SelectionChanged-->CellBeginEdit--->CellLeave-->CellEndEdit-->Leave