获取 Datagridview comboBox 中所选项目的 ID 并显示依赖于 Selectedvalue 的表单

Get the ID of selected item in Datagridview comboBox and show a form depend on Selectedvalue

在组合框中获取所选ID的ID,然后根据ID的值显示表单。

我有一个 DataGridView,里面有几列和一个组合框。我为此使用了两个数据表。 dgv 1 用于 dgv 中的数据,另一个是组合框中的项目。我想要发生的是,当用户在组合框中选择一个状态时,它将获取项目的 ID,然后如果 ID = 0,表单将显示用户需要填写。

Private Sub dgvPassed_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs)
    Dim comboCell As ComboBox = CType(e.Control, ComboBox)
    If (Not (comboCell) Is Nothing) Then
        AddHandler comboCell.SelectedIndexChanged, AddressOf Me.comboCell_SelectedIndexChanged
    End If

End Sub

Private Sub comboCell_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim cellText As String = dgvPassed.CurrentRow.Cells(7).Value.ToString
    'retrieve data from database using this cellText
End Sub

我尝试使用它并在其中放置断点,但在 运行 并单击 datagridview 组合框后,断点甚至没有触发。

组合框 Q 已被问过几次,例如这里;

但这里有一些代码(假设有两个 DGV 列 Id 和 Status)。您没有说明 Status 是否是存储在数据库中的值,或者您是否只是将该列用作某种指示器(如果是指示器,下面的代码需要在编辑表单后将值重置回 "done" ETC)。

没关系,当您用自己的数据源替换数据源时,您可以对列行为进行排序。

Public Class Form1


    Public Class Sample

        Public Property Id As Integer
        Public Property Status As String


        Public Sub New(id As Integer, status As String)
            Me.Id = id
            Me.Status = status
        End Sub

    End Class


    Dim Source As New List(Of Sample)({New Sample(0, "Done"), New Sample(1, "Done"), New Sample(2, "Done"), New Sample(3, "Done")})



    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        DataGridView1.DataSource = Source

    End Sub


    Private Sub DataGridView1_CurrentCellDirtyStateChanged(ByVal sender As Object, ByVal e As EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged

        If DataGridView1.IsCurrentCellDirty Then
            DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
            DataGridView1.BeginEdit(True)
        End If
    End Sub


    Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged

        If e.ColumnIndex < 0 OrElse e.RowIndex < 0 Then Exit Sub


        Dim ComboCell As DataGridViewComboBoxCell = DirectCast(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex), DataGridViewComboBoxCell)

        If ComboCell?.Value?.ToString = "Edit" Then

            'Get ID (Hard-coded to 0 as an example)
            Dim IdCell As DataGridViewTextBoxCell = DirectCast(DataGridView1.Rows(e.RowIndex).Cells(0), DataGridViewTextBoxCell)

            If IdCell?.Value = 0 Then

                'Open your form here 
                Using Openfd As New OpenFileDialog
                    If Openfd.ShowDialog() = DialogResult.OK Then
                        'Do stuff
                    End If
                End Using

            End If

        End If

        '// redraw 
        DataGridView1.Invalidate()

    End Sub

End Class