2013年4月26日 星期五

[技巧] DataGridViewComboBoxColumn 實現 SelectedIndexChanged 事件

程式:
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing

        'If Me.DataGridView1.CurrentCell.OwningColumn.Name = "供應商別" Then
                       Dim comboBox1 As ComboBox = CType(e.Control, ComboBox)
            AddHandler comboBox1.SelectedIndexChanged, _
                New EventHandler(AddressOf ComboBox_SelectedIndexChanged)
        'End If
End Sub

Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        'do something here
         Dim comboBox1 As ComboBox = CType(sender, ComboBox)
         MsgBox(comboBox1.SelectedValue.ToString)
End Sub

DEBUG:
上面的寫法會引發多次觸發,甚至出現 「並未將物件參考設定為物件的執行個體」錯誤。
如果沒有 If Me.DataGridView1.CurrentCell.OwningColumn.Name = "供應商" Then 
則會造成 DGV 上所有的 DataGridViewComboBoxColumn 都可註冊事件。
因此便需更改如下!

Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
     
        If Me.DataGridView1.CurrentCell.OwningColumn.Name = "供應商" Then
            Dim comboBox1 As ComboBox = CType(e.Control, ComboBox)
            If (comboBox1 IsNot Nothing) Then
                ' Remove an existing event-handler, if present, to avoid
                ' adding multiple handlers when the editing control is reused.
                RemoveHandler comboBox1.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged)

                ' Add the event handler.
                AddHandler comboBox1.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged)
            End If
        End If

End Sub


Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim comboBox1 As ComboBox = CType(sender, ComboBox)
        If CType(sender, ComboBox).SelectedValue IsNot Nothing Then
            MsgBox(comboBox1.SelectedValue.ToString)
        Else
            RemoveHandler comboBox1.SelectedIndexChanged, _
                      New EventHandler(AddressOf ComboBox_SelectedIndexChanged)
        End If
End Sub


參考:
DataGridViewComboBoxEditingControl 類別
DataGridView中comboBox(DataGridViewComboBoxColumn)的事件编写
DataGridViewComboBoxColumn的事件??
如何製作DataGridViewComboBoxColumn SelectedIndexChange
如何给DataGridViewComboBoxColumn写事件
DataGridViewComboBoxColumn的事件
DataGridViewEditingControlShowingEventArgs.Control Property
DataGridViewComboBoxColumn的事件??
DataGridViewComboBoxColumn multiple click SelectedIndexChanged event
如何处理DataGridViewComboBoxCell的SelectedIndexChanged事件?
datagridview 選擇 combobox 值 , 自動帶出資料
commit changed in DataGridView when selection changed in ComboBox
DataGridViewComboBoxColumn Selection Changed

ProcessCmdKey方法让DataGridView按Enter回车键转到下一列的格
(讓ComboBoxColumn在下拉選項時, 解決出現二種模式...)

沒有留言:

張貼留言