Skip to main content
 首页 » 编程设计

c#之如何在 DataGridView 中为列设置密码

2024年02月05日13mengfanrong

我正在尝试在加载表格时对列进行密码处理。

下面的代码加载表格。

//Fills out Student table 
private void loadStudentTable() 
{ 
    SqlConnection conn2 = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True"); 
    conn2.Open(); 
 
    try 
    { 
        SqlCommand cmdDatabase2 = new SqlCommand("Select * from Student", conn2); 
        SqlDataAdapter sda2 = new SqlDataAdapter(); 
        sda2.SelectCommand = cmdDatabase2; 
        DataTable dbdataset2 = new DataTable(); 
        sda2.Fill(dbdataset2); 
        BindingSource bSource2 = new BindingSource(); 
        bSource2.DataSource = dbdataset2; 
        studentGridView.DataSource = bSource2; 
        sda2.Update(dbdataset2); 
        studentGridView.Columns[0].Width = 92; 
        studentGridView.Columns[1].Width = 200; 
        studentGridView.Columns[2].Width = 180; 
        studentGridView.Columns[3].Width = 180; 
        studentGridView.Columns[4].Width = 170; 
        studentGridView.Columns[5].Width = 170; 
        studentGridView.Columns[6].Width = 130;                         
    } 
    catch (Exception ex) 
    { 
        MessageBox.Show(ex.Message); 
    } 
 
    conn2.Close(); 
} 

我正在尝试为 studentGridView.Columns[5].Width = 170; 列设置密码。

有什么帮助或想法吗?

请您参考如下方法:

您需要 CellFormatting你的 DataGridView 事件是这样的

private void studentGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    if (gv_Input.Columns[e.ColumnIndex].Index == 5 && e.Value != null) 
    { 
        studentGridView.Rows[e.RowIndex].Tag = e.Value; 
        e.Value = new String('*', e.Value.ToString().Length); 
    } 
}