我在VB.net(Visual Studio 2010)中有一个DataGridView(称为DataGridViewSecurity),它绑定到DataSet中的DataTable(称为DataTableSecurity)(称为DataSetSecurity)。我添加了一个非绑定列(称为nSecurityComboBox),我根据DataTable中的整数字段(称为nSecLevel)设置了该列。设置组合框后,它不会在组合框中显示任何内容,但是当您选择组合框时,它的项目集合中的5个值显示。
这是我用来将记录添加到DataTable然后设置组合框的代码:
Sub Foo()
.
.
.
DataSetSecurity.Tables(0).Rows.Add(New Object() {sName, sID, sSec})
ComboCell_Select(nRow, 3, DataGridViewSecurity, sSecRecs.nSecLevel)
MessageBox.Show("Value for the combo set at " + DataGridViewSecurity.Rows(nRow).Cells(3).Value.ToString)
.
.
.
End Sub
Private Sub ComboCell_Select(ByVal dgvRow As Integer, _
ByVal dgvCol As Integer, _
ByRef DGV As DataGridView,
ByRef nComboBoxRow As Int16)
Try
Dim CBox As DataGridViewComboBoxCell = CType(DGV.Rows(dgvRow).Cells(dgvCol), DataGridViewComboBoxCell)
Dim CCol As DataGridViewComboBoxColumn = CType(DGV.Columns(dgvCol), DataGridViewComboBoxColumn)
CBox.Value = CCol.Items(nComboBoxRow)
DGV.UpdateCellValue(dgvCol, dgvRow)
'MessageBox.Show("New value in the combo box = " + CBox.Value.ToString)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Foo中的messagebox.show显示组合框的正确值,但不显示任何内容。 有人看到我做错了吗?
感谢。
-NCGrimbo
答案 0 :(得分:0)
如果我理解正确的问题,那么默认情况下,所有值都在组合框中没有正确选择?我想我几天前就遇到过这个问题,这就是我现在所拥有的。
'Create the combobox column
Dim comboBox As New DataGridViewComboBoxColumn()
'Add some stuff to the combobox
comboBox.Items.Add("FirstItem")
comboBox.Items.Add("SecondItem")
'Select the first item
comboBox.DefaultCellStyle.NullValue = comboBox.Items(0)
'Now add the whole combobox to the DataGridView
dgvItems.Columns.Add(comboBox)
希望这有帮助!
答案 1 :(得分:0)
最后,我找到了一些C#代码,我转换为VB.net来解决这个问题。这是代码:
Private Sub DataGridViewSecurity_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridViewSecurity.EditingControlShowing
Dim cellComboBox As ComboBox = TryCast(e.Control, ComboBox)
If cellComboBox IsNot Nothing Then
' make sure the handler doen't get registered twice
RemoveHandler cellComboBox.SelectionChangeCommitted, AddressOf Me.CellComboBoxOnSelectionChangeCommitted
AddHandler cellComboBox.SelectionChangeCommitted, AddressOf Me.CellComboBoxOnSelectionChangeCommitted
End If
End Sub
Private Sub CellComboBoxOnSelectionChangeCommitted(ByVal sender As Object, ByVal e As EventArgs)
Dim comboBox As DataGridViewComboBoxEditingControl = TryCast(sender, DataGridViewComboBoxEditingControl)
If sender Is Nothing Then
Return
End If
If comboBox.SelectedItem Is Nothing Then
Return
End If
If Me.DataGridViewSecurity.CurrentCell.Value = comboBox.SelectedItem Then
Return
End If
Me.DataGridViewSecurity.CurrentCell.Value = comboBox.SelectedItem
End Sub