If you have SQL-Server try out my code sample.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I have DataGridView in my form in that two field are combo box.
When I start the application I get an message :
"he following exception occurred in the DataGridView: System.FormatException:
DataGridViewComboBoxCell value is not valid"
I have tried every thing and can not fix the problem.
Please help me.
If you have SQL-Server try out my code sample.
Hi,
I check your code and it works without problems. Try following demo.
Imports System.Collections.ObjectModel
Imports System.Data.SqlClient
Public Class Form29
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Controls.Add(dgv)
dgv.Columns.Add(New DataGridViewTextBoxColumn With {.HeaderText = "ID", .DataPropertyName = "ID"})
con = New SqlConnection(My.Settings.cnSQL)
LoadCBData()
dgv.Columns.Add(HrsType)
dgv.DataSource = GetData()
End Sub
Dim dgv As New DataGridView With {.Dock = DockStyle.Fill, .AutoGenerateColumns = False}
Dim HrsType As New DataGridViewComboBoxColumn With {.DataPropertyName = "Type"}
Dim con As SqlConnection
Private Sub LoadCBData()
Dim SQLHrsType As String = "SELECT CAST([hrsType] as CHAR(1)) as [hrsType] , CAST([hrsType] as CHAR(1)) + ' ' + [Description] as [HTDescription] FROM [dbo].[HrsType]"
Dim SQLCmd As SqlCommand
SQLCmd = New SqlCommand(SQLHrsType, con)
con.Open()
Dim HrsTypTbl As New DataTableHrsType
HrsTypTbl.Columns.Add("hrsType", Type.GetType("System.String"))
HrsTypTbl.Columns.Add("HTDescription", Type.GetType("System.String"))
Dim HrTyDA As SqlDataAdapter = New SqlDataAdapter(SQLHrsType, con)
HrTyDA.Fill(HrsTypTbl)
HrsType.DataSource = HrsTypTbl
HrsType.ValueMember = "hrsType"
HrsType.DisplayMember = "HTDescription"
con.Close()
End Sub
Private Function GetData() As ObservableCollection(Of Data)
Dim types() As String = {"A", "B", "C"}
Dim rnd As New Random
Dim l As New ObservableCollection(Of Data)
For i = 1 To 10
l.Add(New Data With {.ID = i, .Type = types(rnd.Next(0, types.Count))})
Next
Return l
End Function
Public Class Data
Public Property ID As Integer
Public Property Type As String
End Class
Public Class DataTableHrsType
Inherits DataTable
End Class
End Class
You get error "... DataError event" if your data in database are incorrect. Check your data. If you don't have a record in HrsType corresponding to DataPropertyName-field in DataSource of DataGridView you get this error.
Data in Datasource of DataGridView:
ID: 1, Type:B
ID: 2, Type:C
ID: 3, Type:C
ID: 4, Type:A
ID: 5, Type:C
ID: 6, Type:C
ID: 7, Type:A
ID: 8, Type:B
ID: 9, Type:A
ID: 10, Type:A
Data in DataTable HrsType:
hrsType: A, HTDescription: A Type A
hrsType: B, HTDescription: B Type B