最近在开发一个项目时,要求某一列只能够输入数字,其它的字符都不接受,Microsoft 没有提供这个功能,只能自己用代码实现,在网上找了一下,大多数都在输入完成后才验证的。这样不爽,我这个代码可以在输入进就屏蔽了非数字的字符。主要是在 EditingControlShowing事件中完成 。看代码: public DataGridViewTextBoxEditingControl CellEdit = null; // 声明 一个 CellEdit private void datagridyf_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { CellEdit = (DataGridViewTextBoxEditingControl)e.Control; // 赋值 CellEdit.SelectAll(); CellEdit.KeyPress += Cells_KeyPress; // 绑定到事件 } // 自定义事件 private void Cells_KeyPress(object sender, KeyPressEventArgs e) { if (datagridyf.CurrentCellAddress.X == 2) // 判断当前列是不是要控制的列 我是控制的索引值为2的 列(即第三列) { if ((Convert.ToInt32(e.KeyChar) < 48 || Convert.ToInt32(e.KeyChar) > 57) && Convert.ToInt32(e.KeyChar) != 46 && Convert.ToInt32(e.KeyChar) != 8 && Convert.ToInt32(e.KeyChar) != 13) { e.Handled = true; // 输入非法就屏蔽 } else { if ((Convert.ToInt32(e.KeyChar) == 46) && (txtjg.Text.IndexOf(".") != -1)) { e.Handled = true; } } } } 下面是在输入完成后才验证的 这个主要是在 CellValidating事件中完成 private void datagridyf_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex == datagridyf.Columns["Pric"].Index ) { datagridyf.Rows [e.RowIndex].ErrorText =""; int NewVal=0; if (!int.TryParse (e.FormattedValue.ToString (),out NewVal ) || NewVal <0) { e.Cancel=true ; datagridyf.Rows [e.RowIndex].ErrorText ="价格列只能输入数字"; return ; } } } 下面是VB.NET版本() Dim WithEvents CellEdit As New DataGridViewTextBoxEditingControl Private Sub dgvXXX_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dgvXXX.EditingControlShowing CellEdit = CType(e.Control, DataGridViewTextBoxEditingControl) CellEdit.SelectAll() AddHandler CellEdit.KeyPress, AddressOf Cells_KeyPress End Sub ' Defect fixing for BEACQ00000345 - EdwardGuo Private Sub Cells_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) If dgvXXX.CurrentCellAddress.X = 1 Then If Asc(e.KeyChar) = 8 Then Exit Sub End If If Not (IsNumeric(e.KeyChar) AndAlso e.KeyChar <> ".") Then e.Handled = True End If End If End Sub End Class

评论