【发布时间】:2015-12-11 07:28:14
【问题描述】:
基本上,我不希望用户能够输入 datagridViewComboboxColumn 如果没有匹配,它会自动将文本保存到数据库中,更新 BindingSource 并选择项目。
这是我目前所拥有的。 绑定源:
With acctTitleCombo6
.AutoComplete = True
Try
.DataSource = ds4
.DisplayMember = "desc_description"
.ValueMember = "desc_id"
.DataPropertyName = "desc_id"
.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End With
在 EditingControlShowing 中将组合框样式更改为下拉:
Dim comboBoxColumn As DataGridViewComboBoxColumn = DataGridView2.Columns(0)
If (DataGridView2.CurrentCellAddress.X = comboBoxColumn.DisplayIndex) Then
Dim cb As ComboBox = TryCast(e.Control, ComboBox)
If (cb IsNot Nothing) Then
cb.DropDownStyle = ComboBoxStyle.DropDown
End If
End If
检查输入的文本是否已经在源项目中(CellValidating 事件)。
Dim comboBoxColumn As DataGridViewComboBoxColumn = DataGridView2.Columns(0)
cs2.Open()
Dim comm, comm2, comm3 As New MySqlCommand
comm.Connection = cs2
Dim msgAddDesc As String = "Your description is currently not in the list." & vbNewLine & _
"Would you like to add '"
If (e.ColumnIndex = comboBoxColumn.DisplayIndex) And Not String.IsNullOrWhiteSpace(e.FormattedValue) Then
Dim itemIE As IEnumerator = comboBoxColumn.Items.GetEnumerator
itemIE.Reset()
Dim thisItem As DataRowView
Dim exist As Boolean = False
While itemIE.MoveNext()
thisItem = CType(itemIE.Current(), DataRowView)
Dim valueMember As Object = thisItem.Row.ItemArray(0)
Dim displayMember As Object = thisItem.Row.ItemArray(1)
If displayMember.ToString = e.FormattedValue Then
exist = True
End If
End While
If exist = False Then
If MessageBox.Show(msgAddDesc & e.FormattedValue & "' to the list?", "Does not exist", _
MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
comm.CommandText = "INSERT INTO ref_description(desc_description) " & _
"VALUES(@description)"
With comm.Parameters
.Add("@description", MySqlDbType.VarChar).Value = e.FormattedValue
End With
comm.ExecuteNonQuery()
comm.Parameters.Clear()
End If
End If
End If
cs2.Close()
现在,每当我向数据库中添加新项目时,都会出现此错误,但有时不会:
The following exception occurred in the DataGridView:
System.FormatException: Value '' cannot be converted to type 'System.String'.
at System.Windows.Forms.DataGridViewComboBoxCell.ParseFormattedValue(Object formattedValue, DataGridViewCellStyle cellStyle, TypeConverter formattedValueTypeConverter, TypeConverter valueTypeConverter)
at System.Windows.Forms.DataGridView.PushFormattedValue(DataGridViewCell& dataGridViewCurrentCell, Object formattedValue, Exception& exception)
另一个问题是,我如何在将新项目添加到数据库后更新组合框,然后我还想在用户按 enter 或 tab 时自动选择新项目(仅当有新项目添加到数据库)。
【问题讨论】:
-
把
e.FormattedValue改成e.FormattedValue.ToString(.Add("@description", MySqlDbType.VarChar).Value = e.FormattedValue.ToString)试试 -
我已经尝试过您的建议wingedpanther,但错误仍然存在。
标签: vb.net datagridcomboboxcolumn