【问题标题】:Allow only specific value range in DataGridView Columns' cells仅允许 DataGridView 列的单元格中的特定值范围
【发布时间】:2015-01-29 21:35:29
【问题描述】:

我正在推进这个项目,尽管速度很慢。我的 DataGridView 几乎设置为可以继续进行项目的下一部分的位置。但我发现我需要解决的最后一件事是:

问题

我需要限制用户可以在 DGV 的每一列中输入的值的范围。例如:

  • 第 0 列和第 1 列可以接受 0-3000 之间的值
  • 第 2 列可以接受 0-20000 之间的值
  • 第 3 栏 (0-1000)
  • 第 4 栏 (0-320)

DGV 没有固定数量的行,因为用户可以通过单击按钮添加任意数量的行。我已经看到示例显示用于设置整个 DGV 甚至行中的值范围的类似代码,但我无法找到任何内容或帮助显示如何设置每列的范围值。

我为单元格验证编写了一些代码,以确保只有整数值输入到 DGV 中并且没有单元格为空。有没有办法添加到此代码或修改它以解决我当前的问题?如果是这样,有人可以提供一些帮助让我开始吗? - 谢谢你,新手。

Private Sub LftMtr_Data_Grid_CellValidating(ByVal sender As Object, _
ByVal e _
As DataGridViewCellValidatingEventArgs) _
Handles LftMtr_Data_Grid.CellValidating

    Me.LftMtr_Data_Grid.Rows(e.RowIndex).ErrorText = ""
    Dim newInteger As Integer
    ' Don't try to validate the 'new row' until finished  
    ' editing since there 
    ' is not any point in validating its initial value. 
    If LftMtr_Data_Grid.Rows(e.RowIndex).IsNewRow Then Return
    If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) _
        OrElse newInteger < 0 Then
        e.Cancel = True
        Me.LftMtr_Data_Grid.Rows(e.RowIndex).ErrorText = "Cells must not be null and must equal a non-negative integer"
    End If
End Sub

【问题讨论】:

    标签: vb.net datagridview


    【解决方案1】:

    看到您的验证与在 MSDN 文档中看到的 here 几乎相同,我相信您了解正在发生的一切。请注意,在方法中访问单元格行索引。列索引也可以这样做。由于您要根据列验证单元格值的上限,我们将使用此列索引来设置要检查的上限。

    尝试在 Dim newInteger As Integer 之后但在您的 If 语句之前添加以下代码:

    Dim upperLimit As Integer = 0
    
    Select Case e.ColumnIndex
        Case 0, 1
            upperLimit = 3000
        Case 2
            upperLimit = 20000 
        Case 3
            upperLimit = 1000
        Case 4
            upperLimit = 320
        Case Else
            Debug.WriteLine("You decide what should happen here...")
    End Select
    

    最后,修改你的 If 语句:

    If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) _
        OrElse newInteger < 0 
        OrElse newInteger > upperLimit Then
    

    这应确保检查的每个单元格都保持在其列的可接受值范围内。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多