在 datagridview 中屏蔽密码列

Bar*_*isY 4 c# passwords datagridviewcolumn winforms datagridtextcolumn

我在屏蔽密码列时遇到问题。下面的代码有效,但它不按我想要的方式工作。在编辑它时会屏蔽密码,但是当我完成并继续下一个 datagridviewcell 密码时,密码变得可见。

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{            
        if (  dataGridView1.CurrentCell.ColumnIndex == 5 || dataGridView1.CurrentCell.ColumnIndex == 10)//select target column
        {
            TextBox textBox = e.Control as TextBox;
            if (textBox != null)
            {
                textBox.UseSystemPasswordChar = true;
            }                
        }
        var txtBox = e.Control as TextBox;
        txtBox.KeyDown -= new KeyEventHandler(underlyingTextBox_KeyDown);
        txtBox.KeyDown += new KeyEventHandler(underlyingTextBox_KeyDown);
}
Run Code Online (Sandbox Code Playgroud)

同样在编辑模式下,它应该只屏蔽索引为 5 && 10 的列,但是它屏蔽了所有列。我无法解决这些问题,任何帮助都会很棒。

Nam*_*ình 7

    private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if ((e.ColumnIndex == 5 || e.ColumnIndex == 10) && e.Value != null)
            {
                dataGridView1.Rows[e.RowIndex].Tag = e.Value;
                e.Value = new String('\u25CF', e.Value.ToString().Length);
            }
    }

    private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (dataGridView1.CurrentCell.ColumnIndex == 5 || dataGridView1.CurrentCell.ColumnIndex == 10)//select target column
        {
            TextBox textBox = e.Control as TextBox;
            if (textBox != null)
            {
                textBox.UseSystemPasswordChar = true;
            }
        }
        else
        {
            TextBox textBox = e.Control as TextBox;
            if (textBox != null)
            {
                textBox.UseSystemPasswordChar = false;
            }
        }
        var txtBox = e.Control as TextBox;
        txtBox.KeyDown -= new KeyEventHandler(underlyingTextBox_KeyDown);
        txtBox.KeyDown += new KeyEventHandler(underlyingTextBox_KeyDown);
    }
Run Code Online (Sandbox Code Playgroud)


TH *_*rov 5

假设您的 DataGridView 的名称是 dataGridView1 并且密码列是 1,请将其添加到 CellFormatting:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 1 && e.Value != null)
    {
        e.Value = new String('*', e.Value.ToString().Length);
    }
}
Run Code Online (Sandbox Code Playgroud)