gpt4 book ai didi

c# - 如何在保存数据时屏蔽后从 c# Winforms datagridview 单元格中检索密码

转载 作者:太空宇宙 更新时间:2023-11-03 22:44:48 25 4
gpt4 key购买 nike

我已经使用下面的代码在 datagridview 中屏蔽了我的密码,并且我成功地做到了。

private void gvInstanceDetails_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 4)
{
if (e.Value != null)
{
gvInstanceDetails.Rows[e.RowIndex].Tag = e.Value;
e.Value = new string('\u2022', e.Value.ToString().Length);
}
}
}

private void gvInstanceDetails_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
TextBox t = e.Control as TextBox;
if (t != null)
{
t.UseSystemPasswordChar = true;
}
}

一旦我屏蔽,如果用户没有删除整个文本并重新输入密码,我将无法检索用户在密码字段中输入的值。

例如:- 如果密码类似于 ***** 并且用户替换了最后两个字符并输入 34 然后在保存时我得到的字符串为 ***34。

谢谢

最佳答案

快速修复

EditingControl 使用单元格的 FormattedValue 进行编辑。

作为快速修复,在 EditingControlShowing 处理程序中将 CurrentCellValue 设置为 Text 文本框:

private void DataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 4)
{
var txt = (TextBox)e.Control;
txt.Text = $"{dataGridView1.CurrentCell.Value}";
txt.UseSystemPasswordChar = true;
}
}

更好的选择 - 创建 DataGridViewPasswordColumn

作为更好的选择,创建一个 DataGridViewPasswordColumn 来为您处理逻辑:

public class DataGridViewPasswordColumn : DataGridViewTextBoxColumn
{
public DataGridViewPasswordColumn()
{
this.CellTemplate = new DataGriViewPasswordCell();
}
}
public class DataGriViewPasswordCell : DataGridViewTextBoxCell
{
public override void InitializeEditingControl(int rowIndex,
object initialFormattedValue,
DataGridViewCellStyle dataGridViewCellStyle)
{
base.InitializeEditingControl(rowIndex,
initialFormattedValue, dataGridViewCellStyle);
((TextBox)this.DataGridView.EditingControl).UseSystemPasswordChar = true;
}
protected override void Paint(Graphics graphics,
Rectangle clipBounds, Rectangle cellBounds,
int rowIndex, DataGridViewElementStates cellState,
object value, object formattedValue,
string errorText, DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
var i = $"{formattedValue}".Length;
formattedValue = new string('●', i);
base.Paint(graphics, clipBounds, cellBounds, rowIndex,
cellState, value, formattedValue,
errorText, cellStyle, advancedBorderStyle, paintParts);
}
}

关于c# - 如何在保存数据时屏蔽后从 c# Winforms datagridview 单元格中检索密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50480748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com