Dynamically auto refresh datagridview every 3 seconds vb.net - vb.net

In my form I have a datagridview which needs to be automatically refreshed every 2 seconds without me having to close the application. I have used the following timer code to try and achieve that. I have placed this code in my form load which is also where my datagridview code is:
Dim timer As New Timer()
timer.Interval = 2000
AddHandler timer.Tick, AddressOf timer_Tick
timer.Start()
Private Sub timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
Me.DataGridView1.Refresh()
End Sub
However, all it does is flicker and doesn't actually refresh the datagridview. My datagrid is connected to a Access database and is not binded, I did with SQL. What am I doing wrong?

DGV.Refresh tell the the program to redraw the control. You need to rerun the process that gets your data and recall it.
Private Sub timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
UpdateDGV()
End Sub
Private Sub UpdateDGV()
'run sql stuff in here
End Sub

Related

Close App after 1 minute of inactive time

I want the vb.net app to close after 1 minute of inactive time.
this code will close the app after 1 min for active user as well.
Dim app As Application
Private Sub MainWindow_Loaded(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim aTimer As System.Timers.Timer
aTimer = New System.Timers.Timer()
aTimer.Interval = 60000
AddHandler aTimer.Elapsed, AddressOf OnTimedEvent
aTimer.Enabled = True
End Sub
Private Sub OnTimedEvent(ByVal source As Object, ByVal e As System.Timers.ElapsedEventArgs)
app.Exit()
End Sub
You can try as follow.
Create a System.Timers.Timerin your window.xaml.vb file:
Private WithEvents CloseTimer As New Timers.Timer
In the constructor, add the following lines:
CloseTimer.Interval = 1000 * 5 ' Remember that interval is set in milliseconds
CloseTimer.Start()
Every time the mouse is moved on the window, the timer has to be reset, so use the MouseMove event like this:
Private Sub Window_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
ResetTimer()
End Sub
And define the ResetTimer() subroutine as follow:
Private Sub ResetTimer()
CloseTimer.Stop()
CloseTimer.Start()
End Sub
Obviously you can change / improve that condition: for example, if the user doesn't move the mouse because he's typing in a Textbox, you should manage this condition, too:
Private Sub Window_PreviewKeyDown() Handles Me.PreviewKeyDown
ResetTimer()
End Sub
This will catch all KeyDown event from the window and all its children controls.
Finally add the Timer_Elapsed event, which will be fired when the timer interval elapsed:
Private Shared Sub Timer_Elapsed() Handles CloseTimer.Elapsed
Environment.Exit(0)
End Sub
If you notice there are more conditions to keep the application running, just find the appropriate event and in its subscription call ResetTimer().
Note that this method is quite simple but, depending on the architecture of the application, there may be better methods.

Refresh/Reload Form using timer in VB.NET

I have messed with this long enough and had to come for help. I am reading in some text file values on form_load. I want to refresh/reload the form every 5 minutes (Disregard my test time). The form loads and runs ok, but after a couple of minutes it seems to crash and I get an error at timer.start. The time until it crashes is very random. I don't understand enough yet about timers, so hopefully someone can tell me where I am going wrong here.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim timer = New Timer
timer.Interval = 30 * 1000
NewMethod(timer)
timer.Start()
'''Run other code
End Sub
Private Sub NewMethod(timer As Timer)
AddHandler timer.Tick, AddressOf Timer1_Tick
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Form1_Load(Me, e:=Nothing)
End Sub

How to: Force users to focus a winform before selecting something from it

I am working on a project that uses WinForms, and I am running into concurrency problems when users click controls on a Form while it isn't the active window. My forms refresh whenever a user activates them to prevent them from showing old/dirty info, but if they click a button on an inactive Form the data doesn't get refreshed, which can cause a problem.
I know some programs in windows force you to select the window before you can preform any other actions, is there a way to do this in my VB.NET program?
This code run in my test, but some issues that must be handled to run as our need:
Dim mystts As Boolean = False
Private Sub Form2_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
'here your process, unfortunately this will be performed too after messagebox close back to form2
'for example the process are:
For myCnt As Integer = 1 To 4000
Debug.Print("Test") 'This only for waiting
Next
mystts = False
End Sub
Private Sub Form2_Deactivate(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Deactivate
'we must define the other criteria for make mystts=true, for example if
'we call messageBox.show, we can pass out from this for example we have msgFlag
'before call messageBox set msgFlag=true and after it set msgFlag=false
'and here you add: if msgFlag=true then exit sub
mystts = True
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'if we click this button and myStts=true, the next process will wait until process in form activate finish
MsgBox("this My Process, run after form2 activated and process finish")
End Sub

Looping backgroundworker

I have a vb.net application that I want to be made a) visible and b) topmost when the activewindow is set to my requirements - this part I have covered off fine.
What I want to be able to do is to use the backgroundworker to actively monitor this on a continuous loop - again I have covered this off fine.
The problem I am having is that when I am selecting a combobox, I cannot make a selection due to interference from the bgw - almost like when I click on the combobox to show the list, the bgw seems to almost do a click away from the combobox closing the list.
Any help would greatly be appreciated.
Here is my code:
Private Delegate Sub progressDelegate()
Private Sub frmApp_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.bgwActiveWindow.RunWorkerAsync()
End Sub
Private Sub bgwActiveWindow_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgwActiveWindow.DoWork
Dim CheckWindow As progressDelegate
CheckWindow = New progressDelegate(AddressOf SetAppTopMost)
Me.Invoke(CheckWindow)
System.Threading.Thread.Sleep(100)
End Sub
Private Sub SetAppTopMost()
Dim bol As Boolean
If getActiveWindowTitle.IndexOf("Microsoft Outlook") <> -1 Or _
getActiveWindowTitle.IndexOf(My.Settings.AppName) <> -1 Then
bol = True
Else
bol = False
End If
Me.Visible = bol
Me.TopMost = bol
End Sub
Private Sub bgwActiveWindow_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgwActiveWindow.RunWorkerCompleted
bgwActiveWindow.RunWorkerAsync()
End Sub
as Praveen mentioned, check the state before setting it, to prevent setting focus to the window again. also, don't recreate the backworker thread each time:
Imports System.ComponentModel
Private Sub bgwActiveWindow_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bgwActiveWindow.DoWork
Do
' backworker code
Threading.Thread.Sleep(1000)
Loop While True
End Sub
of course, you'll either have to implement the 'supportscancellation' junk, or simple set a flag in your main thread and poll that on each loop and exit/break if you want to cancel.
you could also use a timer, which won't lock the thread.
i think you should add an additional check in your SetAppTopMost sub.
if Me.Visible = True then exit sub
This line should be 1st line. Since you are trying to show the form every 100ms, you are loosing focus.

Delaying in VB.net

my issue is i need to wait 3-4 seconds after a button has been pressed before i can check for it, here is my code under button1_click:
While Not File.Exists(LastCap)
Application.DoEvents()
MsgBox("testtestetstets")
End While
PictureBox1.Load(LastCap)
I think i'm doing something really simple wrong, i'm not the best at VB as i'm just learning so any explaining would be great!
~Thanks
If the reason you are needing to wait is for the file to be created try using a FileSystemWatcher and respond to the Created and Changed Events that way you are responding to an event rather than arbitrarily waiting a select period of time.
Something like:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
FileSystemWatcher1.Path = 'Your Path Here
FileSystemWatcher1.EnableRaisingEvents = True
'Do what you need to todo to initiate the file creation
End Sub
Private Sub FileSystemWatcher1_Created(sender As Object, e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Created, FileSystemWatcher1.Changed
If e.Name = LastCap Then
If (System.IO.File.Exists(e.FullPath)) Then
FileSystemWatcher1.EnableRaisingEvents = False
PictureBox1.Load(e.FullPath)
End If
End If
End Sub
You can use, although not recommended:
Threading.Thread.Sleep(3000) 'ms
This will wait 3 seconds, but also block everything else on the same thread. If you run this in the form your user-interface will not response until the wait is over.
just as a side note: use MessageBox.Show("My message") instead of MsgBox (latter is from old VB).
If you want your form to continue to function while the 3 seconds pass, you can add a Timer control instead, with some code like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' set the timer
Timer1.Interval = 3000 'ms
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Timer1.Stop()
'add delayed code here
'...
'...
MessageBox.Show("Delayed message...")
End Sub
Drag and drop a Timer control from your toolbox to your form. It's not visible at runtime
or better yet making a wait function using stop watch, this wont halt the process in the same thread like thread sleep
' Loops for a specificied period of time (milliseconds)
Private Sub wait(ByVal interval As Integer)
Dim sw As New Stopwatch
sw.Start()
Do While sw.ElapsedMilliseconds < interval
' Allows UI to remain responsive
Application.DoEvents()
Loop
sw.Stop()
End Sub
usage
wait(3000)
for 3 sec delay
You could use this
Public Sub BeLazy()
For i = 1 To 30
Threading.Thread.Sleep(100)
Application.DoEvents()
Next
End Sub
It will delay for 3 seconds.