Changing button name if file exists? - vb.net

I'm working on a custom GUI, my last step is for the button to change automatically check if the file exists or not on startup. The method below is my download/open button. Any help is appreciated!
Private Sub Button7_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button7.Click
If Dir("DownloadedFile.zip") <> "" Then
Process.Start("DownloadedFile.zip")
Else
WC.DownloadFileAsync(New Uri("http://download852.mediafire.com/3a688rz1a6ig/dk71cs34ihs3v6x/Devil+went+down+to+georgia.rar"), "DownloadedFile.zip")
MsgBox("Starting Download")
End If
End Sub

A subroutine is a seperate method that does not return a value. I would take the If statement out of your click eventhandler and put it in its own method as I stated like this.
Private Sub CheckForFile()
If Dir("DownloadedFile.zip") <> "" Then
Process.Start("DownloadedFile.zip")
Else
WC.DownloadFileAsync(New Uri("http://download852.mediafire.com/3a688rz1a6ig/dk71cs34ihs3v6x/Devil+went+down+to+georgia.rar"), "DownloadedFile.zip")
MsgBox("Starting Download")
End If
End Sub
Call it from your button like this.
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
CheckForFile()
End Sub
Then handle the Shown Event and call it from there. It will run as soon as the initial form is shown
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
CheckForFile()
End Sub
Responding to your comment You need to use the WebClient DownloadFileCompleted Event and the WebClient DownloadProgressChanged Event

Related

VB.net One sub for many events

I'm working on a function in VB.Net where a user can select a supplier from a list.
The idea is that the user will filter the list until the right supplier is visible in a datagridview
the user can then either double click on the row header, the cell content or select a supplier and then click an OK button
I am wondering though, how do I avoid building one Sub for each of the above three events, Can I create one sub that catches all three events?
Private Sub supplierSearchOkButton_Click(sender As Object, e As EventArgs) Handles supplierSearchOkButton.Click
initiativeForm.supplierConcatTextBox.Text = supplierSearchDataGridView.SelectedRows(0).Cells(3).Value.ToString()
Me.Close()
End Sub
Private Sub supplierSearchDataGridView_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles supplierSearchDataGridView.CellContentDoubleClick
initiativeForm.supplierConcatTextBox.Text = supplierSearchDataGridView.SelectedRows(0).Cells(3).Value.ToString()
Me.Close()
End Sub
Private Sub supplierSearchDataGridView_RowHeaderMouseDoubleClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles supplierSearchDataGridView.RowHeaderMouseDoubleClick
initiativeForm.supplierConcatTextBox.Text = supplierSearchDataGridView.SelectedRows(0).Cells(3).Value.ToString()
Me.Close()
End Sub
Personally, I would go with the extra method option mentioned in the comments but, if you want to, you should be able to do this:
Private Sub SetSupplier(sender As Object, e As EventArgs) Handles supplierSearchOkButton.Click,
supplierSearchDataGridView.CellContentDoubleClick,
supplierSearchDataGridView.RowHeaderMouseDoubleClick
initiativeForm.supplierConcatTextBox.Text = supplierSearchDataGridView.SelectedRows(0).Cells(3).Value.ToString()
Me.Close()
End Sub
or even this:
Private Sub SetSupplier() Handles supplierSearchOkButton.Click,
supplierSearchDataGridView.CellContentDoubleClick,
supplierSearchDataGridView.RowHeaderMouseDoubleClick
initiativeForm.supplierConcatTextBox.Text = supplierSearchDataGridView.SelectedRows(0).Cells(3).Value.ToString()
Me.Close()
End Sub
If you're not using any properties of the other e parameters then you can use the most general EventArgs for all three events and if you're not using the parameters at all then you can ditch them altogether. I didn't test this specifically but I'm fairly sure both will work.

Background Cancle Event Form Closing Error

I have a background event that is consistently withdraws data. When I close the form background event doesn't cancel for some reason. If I enable a message in between it does...... I tried to put a time pause, REFRESH, and both. But its only works properly after the message box. I don't really understand why, since button it self to cancel works fine when form is not close. ERROR "Cannot access a disposed object.Object name: 'Form1'." Somehow it doesn't see "False" on closing.
Thanks!
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
RED(False)
'Some other functions - WORK OK
End Sub
Private Sub RED(ByVal reads As Boolean)
bck.WorkerSupportsCancellation = True
If reads = True Then
bck.RunWorkerAsync()
ElseIf reads = False Then
bck.CancelAsync()
bck.Dispose()
End If
End Sub
Private Sub bck_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bck.DoWork
Do
If bck.CancellationPending = True Then --- DOESN'T look like see this without Message BOX
Exit Sub
End If
Me.Invoke(Sub()
'EVENT HERE WERE I AM GETTING AN ERROR --- HOWEVER, Works as a button when called on RED(False) and Works if I put a message BOX
End Sub)
Loop
End Sub
It would appear to be a matter of timing, as is often the case with multiple threads. What I would suggest is that, if the form is closed when the background task is in progress, you cancel the background task and then cancel the close. You can then close again when the background task has completed, e.g.
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Do
If BackgroundWorker1.CancellationPending Then
'Cancel the background work.
Exit Do
End If
'Do the background work.
'...
Loop
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
'Close the form.
Close()
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If BackgroundWorker1.IsBusy Then
'Cancel the background task.
BackgroundWorker1.CancelAsync()
'Do not close the form this time.
e.Cancel = True
End If
End Sub
If you won't always want to close the form when the background task completes then you can indicate that to the RunWorkerCompleted event handler by, for instance, setting e.Result in the DoWork event handler and then testing it in the RunWorkerCompleted event handler, e.g.
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
e.Result = False
Do
If BackgroundWorker1.CancellationPending Then
e.Result = True
'Cancel the background work.
Exit Do
End If
'Do the background work.
'...
Loop
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If CBool(e.Result) Then
'Close the form.
Close()
End If
End Sub
Use PROGRESS REPORT instead of Invoke.
Private Sub bck_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bck.DoWork
Do
If bck.CancellationPending = True Then
Exit Sub
End If
bck.ReportProgress("WHATEVER YOU CAPTURING/VALUES UPDATE")
Loop
End Sub
Private Sub bck_dProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bck.ProgressChanged
YOUR DISPLAY = ("WHATEVER YOU CAPTURING/VALUES UPDATE")
End Sub

Specific keyboard characters to call specific button actions

When I start my program, and push the specified keys to call my button commands, it does not do anything.
The focus remains on one of the buttons and nothing occurs.
I've tried multiple codes from using KeyDown to KeyPress to codes that include vbKey.
I am very new to vb, so it is very likely that I just do understand what I am doing. :(
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.KeyPreview = True
End Sub
Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
If e.KeyCode = "/" Then
Call Button1_Click(sender, e)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnExit.Click
'Close Program
Me.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPMN.Click
'Add +1 to PMN Textbox (txtPMN)
txtPMN.Text = (Val(txtPMN.Text) + 1).ToString()
End Sub
End Class
I would like to simulate the clicking of certain buttons (activate the button code) when I press specific keys on the keyboard. For example: If I press "/" I would like Button1_Click to activate as if I clicked the button with the mouse. Then, if I push my next key ".", I would like Button2_Click to activate.
I do not want to use modifiers like: SHIFT, CTRL, ALT
Please try with keychar like this:
Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
If e.KeyChar = "/" Then
Call Button1_Click(sender, New EventArgs)
End If
end sub
when use keydown, the keycode for "/" key is OEM, depend the keyboard type, so char(e.keycode) may be not "/"

Working sample of Control.VisibleChanged Event in vb.net

I'm struggling to make the MSDN code sample for the Control.VisibleChanged event work: I don't see the MsgBox.
Private Sub Button_HideLabel(ByVal sender As Object, ByVal e As EventArgs)
myLabel.Visible = False
End Sub 'Button_HideLabel
Private Sub AddVisibleChangedEventHandler()
AddHandler myLabel.VisibleChanged, AddressOf Label_VisibleChanged
End Sub 'AddVisibleChangedEventHandler
Private Sub Label_VisibleChanged(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show("Visible change event raised!!!")
End Sub 'Label_VisibleChanged
You need to "wire up" the events to the event handlers.
To start with, to get the code in HideLabel_Click to be called you need it to respond to a click on the button named "HideLabel".
There are two ways to do that: you can use AddHandler or the Handles clause.
To demonstrate the latter:
Option Strict On
Public Class Form1
Private Sub HideLabel_Click(sender As Object, e As EventArgs) Handles HideLabel.Click
myLabel.Visible = False
End Sub
Private Sub myLabel_VisibleChanged(sender As Object, e As EventArgs) Handles myLabel.VisibleChanged
MessageBox.Show("Visible change event raised!!!")
End Sub
End Class
However, you will notice that the message is shown even before the form appears. That is because of what goes on behind the scenes to create the form.
To avoid that happening, you can add the handler after the form has been shown:
Option Strict On
Public Class Form1
Private Sub HideLabel_Click(sender As Object, e As EventArgs) Handles HideLabel.Click
myLabel.Visible = False
End Sub
Private Sub myLabel_VisibleChanged(sender As Object, e As EventArgs)
MessageBox.Show("Visible change event raised!!!")
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
AddHandler myLabel.VisibleChanged, AddressOf myLabel_VisibleChanged
End Sub
End Class
Another way, in VB2015 and later, is to use a "lambda expression" instead of a separate method, although then you cannot disassociate the handler from the event with RemoveHandler:
Option Strict On
Public Class Form1
Private Sub HideLabel_Click(sender As Object, e As EventArgs) Handles HideLabel.Click
myLabel.Visible = False
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
AddHandler myLabel.VisibleChanged, Sub() MessageBox.Show("Visible change event raised!!!")
End Sub
End Class
Craig was kind enough to [and I quote verbatim] call attention to the importance of Option Strict when you add handlers manually using AddHandler. Without it, the "relaxed delegate convention" may allow adding handlers which don't exactly match the event signature that you won't be able to remove later.
Having said that, Option Strict On isn't a complete safeguard: notice how my last example compiles and works even with the wrong method signature for the handler.
[I suspect that the MSDN code sample was first created in C# as part of a larger example, so some parts have been lost in the translation and excerption.]
I get this is old but came across this post when looking for more information on VisibleChanged and couldn't help but notice that the accept answer may be misleading. If you are using a designer to create your Form and place objects on it, then the accepted answer will be fine. In fact you can get rid of the addHandler because the designer handles that for you. All you would need to do is use a handles clause with your label.
Private Sub Button_HideLabel(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
myLabel.Visible = False
End Sub 'Button_HideLabel
Private Sub Label_VisibleChanged(ByVal sender As Object, ByVal e As EventArgs) Handles myLabel.VisibleChanged
MessageBox.Show("Visible change event raised!!!")
End Sub 'Label_VisibleChanged
Where the issue lies with the accepted answer is if you arn't using a designer. Adding handle clauses to "wire up" simply won't work (we can make it work and if anyone is interested in that I'll be happy to post a code snippet of that, but it's not how the accepted answer lays it out). In your case all you need to do is call AddVisibleChangedEventHandler() to set up the handler. that's it. you could have done this by calling it in MyBase.Load
Private Sub Load_Form(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
AddVisibleChangedEventHandler()
End Sub
Private Sub Button_HideLabel(ByVal sender As Object, ByVal e As EventArgs)
myLabel.Visible = False
End Sub 'Button_HideLabel
Private Sub Label_VisibleChanged(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show("Visible change event raised!!!")
End Sub 'Label_VisibleChanged
Private Sub AddVisibleChangedEventHandler()
AddHandler myLabel.VisibleChanged, AddressOf Label_VisibleChanged
End Sub
Once again I know this is dated but couldn't help but notice that (more or less assuming) that you are trying to get a msgBox to appear when you click a label. That is you click a label and then toggled the visibility of another label. The other label is the one where the event handler is on for visibility change. So that inevitably gets called when clicking the original label. IF you only want this msgBox to appear when clicking that label and not when the form loads as well, you should change the addHandler statement so that you are adding a handler on the click event.
Private Sub Load_Form(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
AddVisibleChangedEventHandler()
End Sub
Private Sub Label_VisibleChanged(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show("Visible change event raised!!!")
End Sub 'Label_VisibleChanged
Private Sub AddVisibleChangedEventHandler()
AddHandler otherLabel.Click, AddressOf Label_VisibleChanged
End Sub 'AddVisibleChangedEventHandler
Also Option Strict On has nothing to do with addhandler (From my understanding, could be wrong. please enlighten me if that is the case). Option Strict On is only checking to see that you arn't implicitly typecasting. So for example:
Dim a As Double
Dim b As Integer
a = 10
b = a
results in an error when Option Strict is On but is totally legal if it is off. So in the case of you leaving off the handles clause, you'll never be implicitly typecasting and therefore is not needed.
Hope this helps anyone who sees this question

result of a modal form in vb.net

I create a form 'frmX' and i call it as a modal form :
res = frmX.ShowDialog()
This form has 3 buttons, Abort(3), Retry(4) and Ignore(5), but when the form opens, all the buttons on the first click return 2.
I don't know why this occurs--all of the buttons has their property DialogResult right.
*Private Sub btnIgnorar_Click(sender As Object, e As EventArgs) Handles btnIgnorar.Click
btnIgnorar.DialogResult = DialogResult.Ignore
End Sub
Private Sub btnAbortar_Click(sender As Object, e As EventArgs) Handles btnAbortar.Click
btnAbortar.DialogResult = DialogResult.Abort
End Sub
Private Sub btnReintentar_Click(sender As Object, e As EventArgs) Handles btnReintentar.Click
btnReintentar.DialogResult = DialogResult.Retry
End Sub*
Can someone help me?
Could do with seeing a bit more context, but the following should do what I think you want:
Private Sub btnIgnorar_Click(sender As Object, e As EventArgs) Handles btnIgnorar.Click
DialogResult = DialogResult.Ignore
Close
End Sub
This will close the dialog and return the associated result code to the caller. As to the original code, it seems a bit strange setting the values in the buttons click handlers?
The error comes from the fact that you set the DialogResult of the buttons. You must set the DialogResult of the form !
You actually have more than one option.
Option 1 : Set the Form.DialogResult
Private Sub btnIgnorar_Click(sender As Object, e As EventArgs) Handles btnIgnorar.Click
Me.DialogResult = DialogResult.Ignore
End Sub
Private Sub btnAbortar_Click(sender As Object, e As EventArgs) Handles btnAbortar.Click
Me.DialogResult = DialogResult.Abort
End Sub
Private Sub btnReintentar_Click(sender As Object, e As EventArgs) Handles btnReintentar.Click
Me.DialogResult = DialogResult.Retry
End Sub
Option 2 : Set the Button.DialogResult
Public Sub New()
InitializeComponents()
'Your init code here
'...
'By setting the buttons DialogResults, you don't even have to handle the click events
btnIgnorar.DialogResult = DialogResult.Ignore
btnAbortar.DialogResult = DialogResult.Abort
btnReintentar.DialogResult = DialogResult.Retry
End Sub
'However, if you need to do some stuff before closing the form, you can
Private Sub btnAbortar_Click(sender As Object, e As EventArgs) Handles btnAbortar.Click
'Do some stuff
'You don't need the following line, as it will be done implicitly
'Me.DialogResult = DialogResult.Abort
End Sub