在ComboBox
中使用DataGridView
:
实施:
当使用点击任意行时, DataGridView
与数据表绑定,而此行单元格元素转换为ComboBox
,现在用户可以选择ComboBox
元素。
问题:
它适用于所有情况,
dgvTables(e.ColumnIndex, e.RowIndex) = l_cmbTableList
但是当e.ColumnIndex
和e.RowIndex
具有相同的值时会出现问题,此时ComboBox
列表项看起来很跳跃,用户无法选择此ComboBox
项
第一次。
代码:
1
Private Sub dgvTables_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvTables.CellClick
If e.ColumnIndex > -1 Then
If dgvTables.Columns(e.ColumnIndex).Name.Contains("TableCaption") Then
dgvTables(e.ColumnIndex, e.RowIndex) = l_cmbTableList ' Problem is coming at that point, dropdown list is jumpy, user not able to select item .
l_cmbTableList.DisplayMember = CONST_TableCaption
l_cmbTableList.ValueMember = CONST_TableCaption
l_cmbTableList.DataSource = dt
l_cmbTableList.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
End If
2
Private Sub dgvTables_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dgvTables.EditingControlShowing
'Set the value of the object
cmbEditingComobTables = CType(e.Control, ComboBox)
If Not cmbEditingComobTables Is Nothing Then
AddHandler cmbEditingComobTables.SelectedIndexChanged, AddressOf editingCombo_SelectedIndexChanged
cmbEditingComobTables.DrawMode = DrawMode.OwnerDrawFixed
AddHandler cmbEditingComobTables.DrawItem, AddressOf cmb_DrawItem ' This attached event will fire and set the color of combo box item
End If
3
Private Sub cmb_DrawItem(ByVal sender As System.Object, ByVal e As DrawItemEventArgs)
If Not e.Index = -1 Then
Dim cmb As ComboBox = DirectCast(sender, ComboBox)
Dim dr As DataRowView = DirectCast(cmb.Items(e.Index), DataRowView)
e.DrawBackground()
e.Graphics.DrawString(dr(cmb.DisplayMember).ToString(), e.Font, New SolidBrush(Color.Gray), e.Bounds.X, e.Bounds.Y)
End If