如何能夠在Datagridview中ComboBox類型的儲存格中輸入資料?

來源:互聯網
上載者:User

看了很多文章,大部分都是重寫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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.