Hello!
I really hope somebody can help me!
I'm trying to build a layered solution, with a class project as data layer (project B) anda windows form project (project A)as user interface. On the data layer part, I would like to use the SQLDependency to keep my datasets always in sync with the database.
On the form (project A) i have the following code:
Public Class Form2
Private WithEvents mCinemas As CS_DataLayer.clsCinemas
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LoadData()
End Sub
Private Sub mCinemas_DataChanged() Handles mCinemas.DataChanged
LoadData()
End Sub
Private Sub LoadData()
If IsNothing(mCinemas) Then
mCinemas = New CS_DataLayer.clsCinemas
End If
DataGridView1.DataSource = mCinemas.Cinemas
DataGridView1.Refresh()
End Sub
End Class
And the code from clsCinemas (project B):
Imports System.ComponentModel
Imports System.Data.SqlClient
Public Class clsCinemas
Private connection As SqlConnection
Private command As SqlCommand
Private _cinemas As DataSet
Public Event DataChanged()
Public Property Cinemas() As DataSet
Get
Return _Cinemas
End Get
Set(ByVal value As DataSet)
_Cinemas = value
End Set
End Property
Public Sub New()
SqlDependency.Start(My.Settings.ConnectionString)
If connection Is Nothing Then
connection = New SqlConnection(My.Settings.ConnectionString)
End If
If command Is Nothing Then
command = New SqlCommand("SELECT name FROM tblTest", connection)
End If
If _cinemas Is Nothing Then
_cinemas = New DataSet()
End If
GetData()
End Sub
Private Sub GetData()
_cinemas.Clear()
command.Notification = Nothing
Dim dependency As New SqlDependency(command)
AddHandler dependency.OnChange, AddressOf dependency_OnChange
Using adapter As New SqlDataAdapter(command)
adapter.Fill(_cinemas)
End Using
End Sub
Private Sub dependency_OnChange(ByVal sender As Object, ByVal e As SqlNotificationEventArgs)
Dim dependency As SqlDependency = CType(sender, SqlDependency)
RemoveHandler dependency.OnChange, AddressOf dependency_OnChange
GetData()
RaiseEvent DataChanged()
End Sub
Protected Overrides Sub Finalize()
SqlDependency.Stop(My.Settings.ConnectionString)
If connection IsNot Nothing Then
connection.Close()
End If
MyBase.Finalize()
End Sub
End Class
When I try to run the application, I get the following error message:
"Cross-thread operation not valid: Control 'DataGridView1' accessed from a thread other than the thread it was created on."
Can somebody please help me, as I don't know what is going wrong. It's probably something really easy !?!
Thank you very much!