使用 VB.Net 验证 DataGridView 单元格中输入的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25831615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:12:54  来源:igfitidea点击:

Validating entered values in DataGridView Cell using VB.Net

vb.netdatagridview

提问by user3290334

I'm using VB.Net 2008 and trying to validate a certain cell with certain values like:

我正在使用 VB.Net 2008 并尝试使用某些值验证某个单元格,例如:

In DataGridView1 i want to check the entered data in column 1 and cell 1 if it's less than 10 or not so i used the following code

在 DataGridView1 中,我想检查第 1 列和单元格 1 中输入的数据是否小于 10,因此我使用以下代码

Private Sub DataGridView1_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating

    If DataGridView1.CurrentCell.ColumnIndex = 1 Then
        If DataGridView1.Rows(e.RowIndex).Cells(1).Value < 10 Then
            DataGridView1.Rows(e.RowIndex).ErrorText = "Not Less Than 10"
            e.Cancel = True
        End If
    End If

End Sub

The problem is: every time i try to enter any value in this cell it see nothing (Empty Value) unless if it was already has a value before i start to edit it and always use this value regardless of any new value i write

问题是:每次我尝试在此单元格中输入任何值时,它什么也看不到(空值),除非它在我开始编辑之前已经有一个值,并且无论我写什么新值,都始终使用该值

so how do i validate those cells to not allow users to leave this cell unless it get the right value

那么我如何验证这些单元格以不允许用户离开该单元格,除非它获得正确的值

Note : CellValidated is working perfectly but it has no e.cancel to prevent users from leaving this cell

注意:CellValidated 运行良好,但没有 e.cancel 来防止用户离开此单元格

回答by Gabriel Stancu

I know this is old, but in order to validate the actual value you need to use DataGridView1.Rows(e.RowIndex).Cells(1).FormattedValue, which will give you the modified value. By using DataGridView1.Rows(e.RowIndex).Cells(1).Valueyou will always get the previous value (uneditted, if the cell is editted for the first time you will get the empty value you see). Note that the FormattedValue works only in the CellValidating method. Hope this helps anyone who passes by this question. ^^

我知道这是旧的,但为了验证您需要使用的实际值DataGridView1.Rows(e.RowIndex).Cells(1).FormattedValue,它将为您提供修改后的值。通过使用,DataGridView1.Rows(e.RowIndex).Cells(1).Value您将始终获得前一个值(未编辑,如果第一次编辑单元格,您将获得您看到的空值)。请注意,FormattedValue 仅适用于 CellValidating 方法。希望这可以帮助任何通过这个问题的人。^^