看了很多文章,大部分都是重寫ComboBoxCell,下面是一個不錯的方法,在園子裡看到的貼子,有興趣的朋友可以找一下原帖.
預設情況下,DataGridViewComboBoxCell不接受使用者的輸入值。但有時確實有向ComboxBox輸入資料的需要。實現這個功能,你需要做兩件事。一是將ComboBox編輯控制項的DropDownStyle屬性設定為DropDown,使使用者可以進行輸入(否則只能進行選擇);二是確保使用者輸入的值能夠添加到ComboBox的Items集合。這是因為ComboBoxCell的值必須在Items集合中,否則會觸發DataError事件,而適合添加新值到Items集合的地方是CellValidating事件處理函數:
代碼
Private Sub dataGridView1_CellValidating(ByVal sender As Object, ByVal e As DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
If e.ColumnIndex = Column1.DisplayIndex Then
'Column1是Combobox列的列名
If Not Me.Column1.Items.Contains(e.FormattedValue) Then
Me.Column1.Items.Add(e.FormattedValue)
End If
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = e.FormattedValue '這行是我後來加的,因為好像進行上面的操作後單格的值就會丟失.期待更好的辦法.
End If
End Sub
Private Sub dataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
If Me.DataGridView1.CurrentCellAddress.X = Column1.DisplayIndex Then
Dim cb As ComboBox = TryCast(e.Control, ComboBox)
If cb IsNot Nothing Then
cb.DropDownStyle = ComboBoxStyle.DropDown
End If
End If
End Sub