如何在gridview中创建类型密码列?

我正在创建一个应用程序,用户在其中选择文件并提供打开该文件的凭据。 为此,我在gridview中创建了三列。
用户在密码栏中输入密码。
我想显示*代替字符,就像我们可以创建一个密码类型的文本框。
我在GridView_CellClick事件上尝试了这段代码:

 if (GridView.Columns[e.ColumnIndex].HeaderText == "Password") { txtPassword[e.RowIndex] = new TextBox(); txtPassword[e.RowIndex].Name = "txtPassword"+e.RowIndex; txtPassword[e.RowIndex].PasswordChar = '*'; txtPassword[e.RowIndex].Visible = true; txtPassword[e.RowIndex].TextChanged += new if (GridView.CurrentCell.Value == null) txtPassword[e.RowIndex].Text = ""; else txtPassword[e.RowIndex].Text = GridView.CurrentCell.Value.ToString(); txtPassword[e.RowIndex].Location = GridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex + 1, false).Location; txtPassword[e.RowIndex].Size = GridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex + 1, false).Size; txtPassword[e.RowIndex].Visible = true; txtPassword[e.RowIndex].Focus(); } 

但在上面的解决方案中显示字符。
我怎么解决这个问题?

我认为应该可以处理EditingControlShowing事件并在处理程序中添加以下代码:

 if(e.ColumnIndex == 2) { TextBox tb = e.Control as TextBox; if (tb != null) { tb.PasswordChar = '*'; } } 

CellFormatting事件处理程序代码:

 if(e.ColumnIndex = 2) { if(e.Value != null) { e.Value = New string("*", e.Value.ToString().Length); } } 

在这种情况下,e应该有一个ColumnIndex属性:)

一种解决方案是创建自己的单元格类型并将该类型分配给您的密码列。 例如,您只会向其添加标准TextBoxPassword,然后它应该按您的意愿工作。

在MSDN上有更详细的描述和源代码可用。

你只需要创建你所获得的CellTemplate 。

您可以创建自定义单元格和列,并使用带有密码掩码的文本框作为编辑控件。

要在离开编辑模式时返回清除文本,可以将实际密码值存储在单元格的单独属性中,并且在GetFormattedValue事件中(我相信)您可以返回由完全“*”字符组成的字符串掩盖常规显示。

 Protected Overrides Function GetFormattedValue(ByVal value As Object, ByVal rowIndex As Integer, ByRef cellStyle As System.Windows.Forms.DataGridViewCellStyle, ByVal valueTypeConverter As System.ComponentModel.TypeConverter, ByVal formattedValueTypeConverter As System.ComponentModel.TypeConverter, ByVal context As System.Windows.Forms.DataGridViewDataErrorContexts) As Object Dim strVal As String strVal = New String(CChar("*"), value.ToString.Length) Return MyBase.GetFormattedValue(strVal, rowIndex, cellStyle, valueTypeConverter, formattedValueTypeConverter, context) End Function Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, _ ByVal initialFormattedValue As Object, ByVal dataGridViewCellStyle As DataGridViewCellStyle) MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, _ dataGridViewCellStyle) Dim ctl As PasswordTextBoxEditingControl = _ CType(DataGridView.EditingControl, PasswordTextBoxEditingControl) If IsDBNull(Me.Value) Then ctl.Text = "" Else ctl.Text = CType(Me.Value, String) ctl.PasswordChar = "*" ctl.Mask = "*" End If End Sub 

有关您要执行的操作的更多信息,请访问: http : //www.vbforums.com/showthread.php?t = 554744