Nii
Nii

Reputation: 568

update user interface when database data is changed

is there any way possible where a control on the form (ex: datagrid) is automatically updated once a data has been inserted on the Database?

Example:

  1. Person A has a dashboard on his computer which monitors a high level inventory breakdown.
  2. Person B, C, and D added a new item to the inventory database respectively.
  3. Person B, C, and D's action should immediately reflect on Person A's (realtime) with no timers, intervals, or manual refresh.

is it possible to achieve this via C# WinForms? I've studied and tried things about SignalR but i don't think its that of what i want/need.

Thanks.

Upvotes: 4

Views: 2873

Answers (2)

nlv
nlv

Reputation: 831

I would suggest using SignalR and SQL event listeners.

Step 1: You could define your entity model in c# (there are tools to do reverse engineering which would save you time writing the context yourself).

Step 2: Configure SignalR Hub. Store all user connections in an objects, this has a basic tutorial how to do that.

Step 3: You can then override SaveChangesAsync method, do some checks inside to determine whats being chanegd and if its the model that you are interested in you can fire the changes to a SIgnalR hub method and that will push all the changes to a client side JS.

Once you received it in JS you can perform the changes to the datagrid.

Upvotes: 2

boop_the_snoot
boop_the_snoot

Reputation: 3247

Assuming your DB is MSSQL.

I'm sorry to say but there is NO way you can achieve what you want without hitting SQL DB with polling requests. You may try SQLDependency as mentioned by @Cyber Progs in the comment, but I still don't think that will do much good. But hey, trying does no harm :) So go for it.

SQL is more of a kind where you get what you ask. Not the other way around. So unless and until you make a polling request to the DB to get the details of whatever table you want by using a timer or manual refresh, SQL by itself won't pass an update to your program.

As you have tried and left SignalR, I would suggest to use a Timer + Multithreading. Apart from that I don't see a way more suitable for what you require to be achieved.

Else a more convenient option would be to use FileSystemWatcher which resides in System.IO.FileSystemWatcher. What you can do is create a SQL Trigger over the table that you want to get notified about.

This trigger would eventually do nothing but change(modify) a local/network file whenever an INSERT, UPDATE, DELETE query has been run.

The file itself would have nothing in its content, it's just that its modified date would change on every Trigger run.

You can now code in your application using FileSystemWatcher to watch for this(local/network) file. If it's modified just do a quick poll to the DB and fetch the latest data.

Upvotes: 2

Related Questions