【发布时间】:2014-07-26 18:23:54
【问题描述】:
我的表单中有一个 DataGridView,它有一个 ComboBoxColumn,其中包含一个硬编码的植物列表。如果选择“其他”,我还为用户提供添加其他植物的选项。
当用户选择“其他”时,他将新的草名放在消息框中。
但是,单击“确定”后,新名称不会添加到组合框中。 (植物间距的值以编程方式添加)
只有单击表格中的另一个单元格才能添加新名称。
如何在不失去焦点的情况下更新组合框?
这是我在单击组合框时使用的代码
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
CB = TryCast(e.Control, System.Windows.Forms.ComboBox)
If CB IsNot Nothing Then
RemoveHandler CB.SelectedIndexChanged, AddressOf DGVComboIndexChanged
AddHandler CB.SelectedIndexChanged, AddressOf DGVComboIndexChanged
End If
' Other event handlers removed and added here
End Sub
Private Sub DGVComboIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
' Do what you like with the current ComboBoxCell.
'System.Windows.Forms.MessageBox.Show(String.Format( _
'"The SelectedIndex was changed in ComboBoxCell: {0}" & _
'Environment.NewLine & _
'"The current item is: {1}", _
'Me.DataGridView1.CurrentCellAddress.ToString(), _
'CB.SelectedItem.ToString()))
Dim TryAgain As Boolean = True
Dim Letters As String = "abcdefghijklmnopqrstuvwxyz1234567890"
Dim ComboColumn As System.Windows.Forms.DataGridViewComboBoxColumn
ComboColumn = DataGridView1.Columns(0)
Try
If CB.SelectedItem.ToString = "Other" Then
While TryAgain
OtherGrass = Microsoft.VisualBasic.InputBox("Enter the alternate plant name", "Other plant", "")
If OtherGrass = "" Then
'return the cell to ""
DataGridView1.CurrentRow.Cells(0).Value = ""
Exit Sub
End If
For i As Integer = 1 To Len(Letters)
If InStr(LCase(OtherGrass), Mid(Letters, i, 1)) > 0 Then
TryAgain = False
Exit For
End If
Next
For i As Integer = 0 To ComboColumn.Items.Count - 1
If LCase(OtherGrass) = LCase(ComboColumn.Items.Item(i).ToString) Then
TryAgain = True
System.Windows.Forms.MessageBox.Show("This plant has already been added.")
End If
Next
End While
'ReDim Preserve Grasses(Grasses.GetUpperBound(0) + 1)
'Grasses(Grasses.GetUpperBound(0)) = OtherGrass
ComboColumn.Items.Add(OtherGrass)
End If
If DataGridView1.CurrentRow.Cells(1).Value Is Nothing Then
DataGridView1.CurrentRow.Cells(1).Value = txtSpacMult.Text
End If
'If CB.SelectedItem.ToString <> "" Then
' For i As Integer = 1 To DataGridView1.Columns.Count - 2
' Dim temp As Boolean = Me.DataGridView1.Rows(DataGridView1.CurrentRow.Index).Cells(i).ReadOnly
' Me.DataGridView1.Rows(DataGridView1.CurrentRow.Index).Cells(i).ReadOnly = False
' temp = Me.DataGridView1.Rows(DataGridView1.CurrentRow.Index).Cells(i).ReadOnly
' Next
'End If
EnableRun()
Catch ex As Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
【问题讨论】:
-
试试这个:将新文本添加到 ComboColumn 后,将 selectedindex/sletedItem 设置为刚刚添加的。
-
我尝试通过添加
CB.SelectedIndex = ComboColumn.Items.Count - 1,但此时具有SelectedIndex方法的组合框CB没有新项目,所以我会得到一个超出范围的异常
标签: vb.net visual-studio-2010 datagridview