Create real-time data to client using SQL server in vb.net
1 Answer
1Hi @datsam! Welcome to the forum! ![]()
To push real-time updates from SQL Server to a VB.NET desktop app (like WinForms or WPF), the best built-in tool is SqlDependency using SQL Server’s Service Broker.
Here is the standard workflow to set it up:
1. Enable Service Broker in SQL Server
Run this once in SQL Server Management Studio (SSMS):
ALTER DATABASE YourDatabaseName SET ENABLE_BROKER;
2. Start the Listener in VB.NET
Start the listener when your application loads (and remember to call .Stop() when closing):
SqlDependency.Start(connectionString)
3. Attach a Dependency to your Query
Note: Your query must use two-part table names (e.g., dbo.MyTable) and cannot use *.
Private Sub GetData()
Using conn As New SqlConnection(connectionString)
Using cmd As New SqlCommand("SELECT Id, Status FROM dbo.Orders", conn)
' Clear old notifications and attach a new one
cmd.Notification = Nothing
Dim dep As New SqlDependency(cmd)
AddHandler dep.OnChange, AddressOf OnDatabaseChange
conn.Open()
' Load your data into a DataTable or DataGridView here
End Using
End Using
End Sub
4. Handle Changes
When SQL Server detects a change, the event triggers:
Private Sub OnDatabaseChange(sender As Object, e As SqlNotificationEventArgs)
' This fires on a background thread, so use Invoke to update UI
Me.Invoke(Sub() GetData())
End Sub
(If you are building a web app instead of desktop, you can pair this with ASP.NET SignalR to push updates straight to web browsers!)
Would you like a complete, ready-to-run WinForms sample with the UI thread handling included? Just hit Reply! ![]()
Provide me the code for vb.net
– datsam