.net - DataGridView 仅数字单元格?

标签 .net vb.net winforms datagridview

我是 winforms 的新手..我试图将 DataGridView 的两列设置为仅数字.. 我不希望用户能够在单元格中输入任何内容,除非它是一列中的自然数和另一列中的数值(总是一位小数)。
我认为这很简单……但即使在从 stackoverflow 和其他网站尝试了很多东西之后,我仍然无法实现这一目标。

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 

最佳答案

试试这个代码

 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 事件仅适用于数字
带有十进制值的数字的文本框按键事件

关于.net - DataGridView 仅数字单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19855943/

相关文章:

C# 显示 Windows 窗体

c# - 禁用按钮时如何避免颜色变化?

c# - DataTable.Select() 显示数据表中记录的总和

c# - 通过 System.Data.Linq.DataContext 插入 SQL Server 时出错

mysql - 如何获取MySql数据库中所有列名显示在comboBox中

vb.net - 如何在 VB.Net 2010 中的 double 中使用 null 值?

c# - 在DataGridView中自动构建编号

c# - 记录谁订阅了事件

c# - 如果实现对象不可序列化,我如何序列化基础对象?

javascript - 在自动回发下拉列表后刷新 javascript 代码