屏蔽datagridview中的密码列

本文关键字:密码 datagridview 屏蔽 | 更新日期: 2023-09-27 18:02:29

我有屏蔽密码列的问题。下面的代码工作,但它不是我想要的方式工作。而编辑它做屏蔽密码,但当我完成并继续到下一个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);
}

在编辑模式下,它应该只屏蔽索引为5的列&&10然而,它掩盖了所有的列。这些问题我解决不了,请您帮忙就太好了。

屏蔽datagridview中的密码列

    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);
    }

假设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);
    }
}