【问题标题】:Add and Delete rows in DataGridView when Checkbox is checked and unchecked选中和取消选中复选框时在 DataGridView 中添加和删除行
【发布时间】:2013-09-20 21:43:12
【问题描述】:

datagridview有GroupGrid和ProductGrid两种。 Groupgrid 包含 3 列。第一个是复选框列。加载 from 时会填充 GroupGrid 中的数据,并将其存储在 gGroupArray 中。当复选框被选中时,我必须通过比较 gGroupArray 和 gProductArray 的 categoryID 以及未选中时的删除行来填充 Productgrid。我必须填充的数据位于名为 gProductArray 的数组中。

将使用哪些事件以及如何完成。如何检查复选框被选中或未选中的条件。我尝试了以下

  Private Sub groupGrid_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GroupGrid.CellClick
    If e.ColumnIndex = 0 And Convert.ToBoolean(GroupGrid(e.ColumnIndex, e.RowIndex).Value) = True Then

        Dim i As Integer = 0
        Dim categoryId As Integer = GroupGrid.Rows(e.RowIndex).Cells("CategoryID").Value()

        If gProductArray.Length < 0 Then Exit Sub

        While i < gProductArray.Length
            If categoryId = gProductArray(i).iCategoryID Then
                ProductGrid.Rows.Add()
                ProductGrid.Rows(i).Cells("ProductGroup").Value() = gProductArray(i).tProductGroup
                ProductGrid.Rows(i).Cells("Product").Value() = gProductArray(i).tProductName

                ProductGrid.Rows(i).Cells("CategoryID").Value() = gProductArray(i).iCategoryID
                ProductGrid.Rows(i).Cells("LicenseProductID").Value() = gProductArray(i).lLicenseProductID
                ProductGrid.Rows(i).Cells("SNRequired").Value() = gProductArray(i).bSNRequired
            End If
            i = i + 1
        End While
    End If
End Sub

【问题讨论】:

    标签: vb.net datagridview vb.net-2010


    【解决方案1】:

    每次单击单元格时都会调用CellClick Event(是否更改复选框无关紧要)。在任何情况下,此事件都会在单元格的值更改之前调用,因此您将获得先前的状态(False 以防检查它)。你最好考虑CellValueChanged Event

    Private Sub GroupGrid_CellValueChanged(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GroupGrid.CellValueChanged
    
        If started AndAlso e.ColumnIndex = 0 AndAlso GroupGrid(e.ColumnIndex, e.RowIndex).Value IsNot Nothing Then
    
            Dim isChecked As Boolean = DirectCast(GroupGrid(e.ColumnIndex, e.RowIndex).Value, Boolean)
            If (isChecked) Then
                'Cell is checked
            Else
                'Cell is not checked
            End If
    
        End If
    
    End Sub
    

    如您所见,我包含一个布尔变量 (started)。它是全局定义的,并在Form Load Event 的末尾设置为true。使用此标志的原因是CellValueChanged Event 可以在Form Load 操作完成之前调用,如果使用任何涉及影响给定DataGridView 的代码会引发错误。您必须记住的另一件事是,在单击复选框后,但在“引入给定值”之后(例如,通过单击任何其他单元格或按进入)。复选框单元格的行为与文本单元格一样:如果您在文本类型单元格中输入字符串,则不会自动存储值(您必须按 Enter 键或选择不同的单元格)。您可能必须想出一些额外的方法来避免最后的副作用,例如:CellClick Event 上的 SendKeys.Send("{ENTER}")(强制在单击/检查后立即存储值)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 2017-06-20
      • 1970-01-01
      相关资源
      最近更新 更多