我有一个DataGridView
,用户在其中更新数据库中的一些数量和价格。问题在于,有时用户可能会使用"."
而不是","
作为小数点分隔符,这会弄乱数据库中的数据(例如,当用户输入"2.7"
后,离开cell
,剩下的值为"27"
)。到目前为止,我已经尝试使用CellValidating
和CellValueChanged
事件,但无法解决问题。 (下面的代码,第一个来自CellValidating
,第二个来自CellValueChanged
)
'CellValidating
If e.FormattedValue.ToString().Contains(".") Then
DataGridViewSample(e.ColumnIndex, e.RowIndex).Value.ToString().Replace(".", ",")
End If
'CellValueChanged
If DataGridViewSample(e.ColumnIndex, e.RowIndex).Value.ToString().Contains(".") Then
DataGridViewSample(e.ColumnIndex, e.RowIndex).Value.ToString().Replace(".", ",")
End If
对不起,如果我的请求看起来很愚蠢,但是我被要求阻止这种用户“错误”。我想以编程方式将"."
替换为","
或进行更新,以使编译器将"."
视为","
(其他解决方法这也被接受)。任何建议都会很棒,祝您有愉快的一天!
答案 0 :(得分:1)
为此,请不要使用格式。
您需要使用单元格中的文本框对象:
'This will represent the content of the cell
Dim editBox As TextBox = Nothing
在datagridview的EditingControlShowing
事件中,您需要获取textbox
对象并添加一个keyDown
事件:
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As
DataGridViewEditingControlShowingEventArgs) Handles
DataGridView1.EditingControlShowing
'Put the column index of the cell
If DataGridView1.CurrentCell.ColumnIndex = 2 Then
If TryCast(e.Control, TextBox) IsNot Nothing Then
editBox = DirectCast(e.Control, TextBox)
'Removing and then adding the keyDown event in the cell
RemoveHandler e.Control.KeyDown, AddressOf Cell_KeyDown
AddHandler e.Control.KeyDown, AddressOf Cell_KeyDown
End If
End If
End Sub
Private Sub Cell_KeyDown(sender As Object, e As KeyEventArgs)
'To commit the changes of the cell
DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
End Sub
然后,在cellLeave
事件中,再次提交单元格的更改,将"."
替换为","
,并将值设置为textbox
:
Private Sub DataGridView1_CellLeave(sender As Object, e As DataGridViewCellEventArgs)
Handles DataGridView1.CellLeave
If DataGridView1.CurrentCell.ColumnIndex = 2 And DataGridView1.CurrentCell.Value IsNot Nothing Then
DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
DataGridView1.CurrentCell.Value = DataGridView1.CurrentCell.Value.ToString.Replace(".", ",")
editBox.Text = DataGridView1.CurrentCell.Value
End If
End Sub
最后,在CellEndEdit
中放入代码以将数据保存在数据库中。
Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
'Code to save in database here...
End Sub
希望这会有所帮助。