我是winforms的新手,我试图将DataGridView的两列设置为仅数字。我不希望用户能够在一个单元格中键入任何内容,除非它是一列中的自然数,另一列中是一个数值(通常是小数点)。我以为这很简单..。但即使在尝试了很多东西,从堆栈溢出和其他网站,我仍然无法做到这一点。
If DataGridView1.CurrentCell.ColumnIndex = 8 Then
If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) AndAlso e.KeyChar <> "."c Then
e.Handled = True
End If
End If
发布于 2013-11-08 10:06:53
试试这段代码
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
If DataGridView1.CurrentCell.ColumnIndex = 2 Then
AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
ElseIf DataGridView1.CurrentCell.ColumnIndex = 1 Then
AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress1
End If
End Sub
Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
If Char.IsDigit(CChar(CStr(e.KeyChar))) = False Then e.Handled = True
End Sub
Private Sub TextBox_keyPress1(ByVal sender As Object, ByVal e As KeyPressEventArgs)
If Not (Char.IsDigit(CChar(CStr(e.KeyChar))) Or e.KeyChar = ".") Then e.Handled = True
End Sub
仅适用于数值的TextBox_keyPress事件
具有十进制值的数值的TextBox_keyPress1事件
发布于 2013-11-08 10:10:49
如果仅关注数据类型验证,则可以使用以下CellValidating事件
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
//e.FormattedValue will return current cell value and
//e.ColumnIndex & e.RowIndex will rerurn current cell position
// If you want to validate particular cell data must be numeric then check e.FormattedValue is all numeric
// if not then just set e.Cancel = true and show some message
//Like this
if (e.ColumnIndex == 1)
{
if (!IsNumeric(e.FormattedValue)) // IsNumeric will be your method where you will check for numebrs
{
MessageBox.Show("Enter valid numeric data");
dataGridView1.CurrentCell.Value = null;
e.Cancel = true;
}
}
}
发布于 2015-03-12 12:47:12
If e.ColumnIndex = 6 Then
If Not IsNumeric(e.FormattedValue) Then
' IsNumeric will be your method where you will check for numebrs
MessageBox.Show("Enter valid numeric data")
DataGridView1.CurrentCell.Value = Nothing
e.Cancel = True
End If
End If
https://stackoverflow.com/questions/19855943
复制相似问题