Complex MsgBoxResult.No function VISUAL BASIC - vb.net

I've made a button1 that if you click on it it starts the timer. In timer_tick I typed Label7.Text = "L O A D I N G". I've made also Exit (Button2). I want to do a code that if Label7.Text = "L O A D I N G" then the msgboxresult.no in button2 will be Button1.Enabled = True . Here is video how I want to do that: http://www.youtube.com/watch?v=4URYhd0xA8I&feature=youtu.be
Here is the code for Button2 (Exit)
Dim msg As String
Dim title As String
Dim style As MsgBoxStyle
Dim response As MsgBoxResult
msg = "Are you sure you want to exit?" ' Define message for exit."
style = MsgBoxStyle.DefaultButton2 Or _
MsgBoxStyle.Question Or MsgBoxStyle.YesNo
title = "Exit"
' Display message.
response = MsgBox(msg, style, title)
If response = MsgBoxResult.No Then
If Label7.Text = "L O A D I N G" Then
Button1.Enabled = True
Button5.Enabled = False
TextBox1.Enabled = True
End If
End If
If response = MsgBoxResult.Yes Then
Me.Close()
End If
I could just simply do:
If response = MsgBoxResult.No Then
Button1.Enabled = True
but it is important that label7 is also mentioned, because label7 shows up when timer1 starts. Please help I don't know what is happening.

Related

Databinding a check box

I have a check box that I binded with a dataset in its properties on my main form. Then on a separate form I have a datagrid that would be the options for each checkbox for a client. The datagrid is good when I look at it. but when I search for a client in the main form sometimes my checkboxes(some of them) will be selected for no reason. I have no coding for this as its all done in the properties except my search button.
Private Sub CmdSearch_Click(sender As Object, e As EventArgs) Handles CmdSearch.Click
Dim iReturn As String
Dim ClientFound As Boolean
Looking = True
ClientFound = False
Place = ClientBindingSource.Position
If Len(TxtSearch.Text) = 6 Then
ClientBindingSource.MoveFirst()
Do Until ClientFound = True
With ClientBindingSource
If Trim(TxtClient.Text) = TxtSearch.Text Then
If TxtSearch.Text = Trim(TxtClient.Text) Then
ClientFound = True
Else
ClientFound = False
End If
Place = ClientBindingSource.Position
Looking = False
Call LRSearch()
ClientBindingSource.Position = Place
Exit Sub
ElseIf Trim(TxtClient.Text) = "ZZTEST" Then
iReturn = MsgBox(TxtSearch.Text & " Not Found", vbOKOnly)
ClientBindingSource.MoveFirst()
Looking = False
Exit Sub
Else
.MoveNext()
End If
End With
Loop
Else
iReturn = MsgBox("Please check your client code for errors " & TxtSearch.Text, vbOKOnly)
TxtSearch.Text = ""
End If
Looking = False
End Sub
I am not sure why the check boxes on my main form have a mind of their own?

Multiple conditions on Timer

Can someone guide me or correct my code. I have multiple conditions in my Timer.
Each Button runs on 1 Timer but each Button clicked has different code or conditions on the timer. The problem is, only one condition will work.
If I click the first Button, the condition for the first Button will run but when I click the second Button, the first condition will still run.
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
''progressbar(KryptonBorderEdge2) timer
KryptonBorderEdge2.Width = KryptonBorderEdge2.Width + 1
Dim curWidth = KryptonBorderEdge2.Width
Dim percentage = (Double.Parse(curWidth) / Double.Parse(404) * 100.0).ToString("#0.00") ''to get percentage
KryptonLabel5.Text = percentage.ToString + " %" ''404 is the max width or the 100%
If KryptonBorderEdge2.Width = 404 Then
Timer1.Enabled = False
End If
''CONNECT button is clicked
If hardwareConnect = True Then
If KryptonLabel5.Text = "50.00 %" Then
Timer1.Interval = 10
Label2.Text = "Hardware Found. Now attempting to connect."
ElseIf KryptonLabel5.Text.Contains("100") Then
KryptonComboBox1.Text = "OMNIKEY"
Label2.Text = "Hardware successfully connected!"
hardwareConnect = False
Timer1.Enabled = False
End If
End If
''CHECK PORT button is clicked
If checkingPort = True Then
If KryptonLabel5.Text.Contains("100") Then
MsgBox("Card format: JCOP S3CC9P9" + vbNewLine + "Connected on COM4", vbOKOnly)
KryptonComboBox2.Text = "JCOP S3CC9P9"
Label2.Text = "..."
checkingPort = False
Timer1.Enabled = False
End If
End If
''REMOVE SAVED DATA is clicked
If KryptonLabel5.Text = "89.00 %" Then
Label2.Text = "Finishing things up."
If KryptonLabel5.Text.Contains("100") Then
removeAll()
MsgBox("Data Successfully Removed!", MsgBoxStyle.OkOnly)
Label2.Text = "..."
Timer1.Enabled = False
End If
End If
''START/WRITE DATA button is clicked
If writeData = True Then
If KryptonLabel5.Text = "20.00 %" Then
Label2.Text = "Blank Card detected."
ElseIf KryptonLabel5.Text = "30.00 %" Then
Label2.Text = "Writing account name..."
ElseIf KryptonLabel5.Text = "40.00 %" Then
Label2.Text = "Inserting ARQC Key and Master Key..."
ElseIf KryptonLabel5.Text = "50.00 %" Then
Label2.Text = "Confirming Expiry Date..."
ElseIf KryptonLabel5.Text = "60.00 %" Then
Label2.Text = "Generating PIN..."
ElseIf KryptonLabel5.Text = "70.00 %" Then
Label2.Text = "Writing PIN and CVV..."
ElseIf KryptonLabel5.Text = "80.00 %" Then
Label2.Text = "Confirming Track1/Track2/Track3..."
ElseIf KryptonLabel5.Text = "90.00 %" Then
Label2.Text = "Finalizing everything. Please wait for a while..."
Timer1.Interval = 1000
ElseIf KryptonLabel5.Text.Contains("100") Then
Label2.Text = "Successfully writing data to the card!"
Timer1.Enabled = False
writeData = False
End If
End If
End Sub
If you want only one condition to be true at a given time, don't use Booleans. Instead, create an enum with possible operations and a variable to store the current operation
Enum Operation
None
HardwareConnect
CheckingPort
WriteData
End Enum
Dim currentOperation As Operation
Now, when a button is clicked set the current operation. Like this only one type of operation can be active.
Private Sub ConnectButton_Click(sender As Object, e As EventArgs) Handles ConnectButton.Click
currentOperation = Operation.HardwareConnect
End Sub
Your sub then looks like this:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'progressbar(KryptonBorderEdge2) timer
KryptonBorderEdge2.Width = KryptonBorderEdge2.Width + 1
Dim curWidth = KryptonBorderEdge2.Width
Dim percentage = (Double.Parse(curWidth) / Double.Parse(404) * 100.0).ToString("#0.00") ''to get percentage
KryptonLabel5.Text = percentage.ToString + " %" ''404 is the max width or the 100%
If KryptonBorderEdge2.Width = 404 Then
Timer1.Enabled = False
End If
If currentOperation = Operation.HardwareConnect Then 'CONNECT button is clicked
...
ElseIf currentOperation = Operation.CheckingPort Then 'CHECK PORT button is clicked
...
End If
' REMOVE SAVED DATA is clicked
If KryptonLabel5.Text = "89.00 %" Then
...
End If
If currentOperation = Operation.WriteData Then
' START/WRITE DATA button is clicked
...
End If
End Sub
Instead of setting the Booleans to False you can set currentOperation = Operation.None
Sub StopOperations()
Timer1.Enabled = False
currentOperation = Operation.None
End Sub

Catching a [Tab] or [Enter] on KeyPress Event

Is it possible to catch the Enter or Tab key in the KeyPress Event?
I am entering a numeric only value on a comboBox, but once this value has been validated I want the user to be able to either Tab or Enter out of the CB once validated, is this possible from within the keyPress? Here's my code;
Private Sub cbCheckAmount_KeyPress(sender As Object, e As KeyPressEventArgs) Handles cbCheckAmount.KeyPress
'Only allowed characters
Dim allowedChars As String = "0123456789."
If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
If e.KeyChar <> ControlChars.Back Then
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character, notify clear and return
nonNumberEntered = True 'Set to True to 'swallow' the keypress and prevent the TextChanged event from firing.
MsgBox("Numbers only", MsgBoxStyle.Exclamation)
cbCheckAmount.Text = ""
cbCheckAmount.Focus()
cbDollarAmount.Text = ""
End If
End If
End If
'If shift key was pressed, it's not a number.
If Control.ModifierKeys = Keys.Shift Then
nonNumberEntered = True
cbCheckAmount.Text = ""
cbCheckAmount.Focus()
End If
End Sub
Private Sub cbCheckAmount_TextChanged(sender As Object, e As EventArgs) Handles cbCheckAmount.TextChanged
'Call the function to create a text line out of the numbers
'Regex to ensure the string contains numbers
Dim t As ComboBox = sender
Dim foo As Decimal
If Decimal.TryParse(cbCheckAmount.Text, foo) Then
'data is good
Dim re As New Text.RegularExpressions.Regex("\d")
If re.IsMatch(cbCheckAmount.Text) Then
If nonNumberEntered = False Then
Dim newNum = cbCheckAmount.Text.Trim
'If there are any leading weird . in the string
newNum = newNum.TrimStart(".")
Dim newStr As String
'Build the array
Dim newDec As String() = newNum.Split(New Char() {"."c})
If newNum.Contains(".") Then
newStr = NumberToText(newDec(0))
cbDollarAmount.Text = newStr & " Dollars and " & newDec(1) & "/100 "
Else
newStr = NumberToText(newDec(0))
cbDollarAmount.Text = newStr & " Dollars and 00/100 "
End If
End If
End If
Else
'data is bad
nonNumberEntered = False
cbCheckAmount.Text = ""
cbCheckAmount.Focus()
cbDollarAmount.Text = ""
End If
End Sub
I'm using VB 2015
Stop and listen. The problem you're trying to solve doesn't exist. Just do it properly in the first place. Handle the Validating event of each control and do your validation there. If validation fails, set e.Cancel to True and the control will retain focus. In the Click event handler of your OK Button or whatever, call the ValidateChildren method and that will raise the Validating event on every control, even if it never received focus. If any controls fail validation, ValidateChildren returns False and you know not to try to use the data. E.g.
Private Sub TextBox1_Validating(sender As Object, e As CancelEventArgs) Handles TextBox1.Validating
Dim value = TextBox1.Text.Trim()
'Data is optional but must be numeric if provided.
If value <> String.Empty AndAlso Not Double.TryParse(value, Nothing) Then
TextBox1.SelectAll()
TextBox1.HideSelection = False
MessageBox.Show("If data is provided, it must be numeric", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Error)
TextBox1.HideSelection = True
e.Cancel = True
End If
End Sub
Private Sub TextBox2_Validating(sender As Object, e As CancelEventArgs) Handles TextBox2.Validating
'Data is required.
If TextBox2.Text.Trim() = String.Empty Then
TextBox2.SelectAll()
TextBox2.HideSelection = False
MessageBox.Show("Data must be provided", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Error)
TextBox2.HideSelection = True
e.Cancel = True
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ValidateChildren() Then
'The data has passed validation so it is safe to use it.
End If
End Sub
If i understand correctly isnt what you want just
If e.KeyChar = ChrW(Keys.Return) or e.KeyChar = Keys.Tab Then
''somethign something''
End If

VB.NET Read 2 checkboxes status from file

I am trying to recover the status of 2 checkboxes.
This 2 checkboxes i made them to work as radiobuttun: While one is checked, the another one uncheck.
I have an external file for the configuration of the program and i want that evrytime that I exit from the program, everything be saved in this file.
For do it I use this code:
Private Sub Form1_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
Dim thefile As String = Application.StartupPath & "\SafetyBox.cfg"
Dim lines() As String = System.IO.File.ReadAllLines(thefile)
lines(1) = "Language_file=" & ComboBox1.Text
If CheckBox1.Checked = True Then
lines(2) = "Status1=" & "1"
Else
lines(2) = "Status1=" & "0"
End If
If CheckBox2.Checked = True Then
lines(3) = "Status2=" & "1"
Else
lines(3) = "Status2=" & "0"
End If
System.IO.File.WriteAllLines(thefile, lines)
End Sub`
And this part working great. Status1 should be the status of checkbox1, while status2 is the status of checkbox2.
The code that is not working is:
Dim path As String = Application.StartupPath & "\SafetyBox.cfg"
If File.Exists(path) Then
Using sr As StreamReader = New StreamReader(path)
Dim linenew As String = sr.ReadLine()
If linenew.Contains("\") Then
TextBox1.Text = linenew
Else
MsgBox("Configura il programma da usare")
End If
Dim lineN As String = sr.ReadLine()
If lineN.Contains("Language_file=") Then
ComboBox1.Text = lineN.Split("=").Last()
End If
If lineN.Contains("Status1=1") Then
CheckBox1.Checked = True
CheckBox2.Checked = False
ElseIf lineN.contains("Status1=0") Then
CheckBox1.Checked = False
CheckBox2.Checked = True
End If
If lineN.Contains("Status2=1") Then
CheckBox1.Checked = False
CheckBox2.Checked = True
ElseIf lineN.Contains("Status2=0") Then
CheckBox1.Checked = True
CheckBox2.Checked = False
End If
sr.ReadToEnd()
sr.Close()
End Using
Can yOu let me understnd where is my mistake? Why when in the .cfg file is wrote correctly Status1=0 and Status2=1, when loading the program i always see checkbox1 checkd and not checkbox2?
Thanks
You wrote that you got the CheckBoxes working as RadionButtons. I suspect that to do this you handled either or both of the events CheckedChanged and CheckStateChanged.
So that when the CheckState is changed, the other Checkbox is set or unset appropriately.
When you load the configuration/state of the form from the file, you are setting the values on the CheckBoxes and subsequently, causing the events to be fired. To prevent the events from being fired you should temporarily remove the event handlers from the Checkbox controls.
Add the lines at the start of your method to load the configuration:
RemoveHandler Checkbox1.CheckStateChanged, AddressOf Checkbox1_CheckStateChanged
RemoveHandler Checkbox2.CheckStateChanged, AddressOf Checkbox2_CheckStateChanged
And, at the end of the method, you will need to re-establish the event handlers by using:
AddHandler Checkbox1.CheckStateChanged, AddressOf Checkbox1_CheckStateChanged
AddHandler Checkbox2.CheckStateChanged, AddressOf Checkbox2_CheckStateChanged
If this is the problem, what you have encountered is a common enough problem when a form has multiple event handlers that respond to xxxChanged events.

Web Browser auto login error (Object reference not set to an instance of an object.)

I have 2 buttons on my form and here is the two bits of code.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If LoggedInToAdastra = True Then
LogOutOfAdastra()
Exit Sub
End If
strUsername = txtUsername.Text
strPassword = txtPassword.Text
LoggedInToAdastra = False
ProgressBar1.Value = 10
Try
WebBrowser1.ScriptErrorsSuppressed = True
WebBrowser1.Navigate("https://nww.awv.nems.nhs.uk/AWA/login.aspx?ReturnUrl=%2fAWA%2fdefault.aspx")
WaitForPageLoad()
WebBrowser1.Document.All("ctl00$MainContent$txtUserName").SetAttribute("value", strUsername)
WebBrowser1.Document.All("ctl00$MainContent$txtPassWord").SetAttribute("value", strPassword)
WebBrowser1.Document.All("ctl00$MainContent$btnLogin").InvokeMember("click")
ProgressBar1.Value = 40
WaitForPageLoad()
ProgressBar1.Value = 80
WebBrowser1.Document.All("ctl00$MainContent$ctl01").InvokeMember("click")
WaitForPageLoad()
ProgressBar1.Value = 100
LoggedInToAdastra = True
txtPassword.Enabled = False
txtUsername.Enabled = False
Button2.Enabled = False
Button1.Text = "Log Out"
Button2.BackColor = Color.MintCream
Button1.BackColor = Color.MintCream
txtPassword.BackColor = Color.MintCream
txtUsername.BackColor = Color.MintCream
ProgressBar1.Value = 0
btnUpdate.Enabled = True
btnDoAll.Enabled = True
btnSearchSelected.Enabled = True
doc = Nothing
Catch ex As Exception
MsgBox("Login Failed")
Button2.BackColor = Color.MistyRose
Button1.BackColor = Color.MistyRose
txtPassword.BackColor = Color.MistyRose
txtUsername.BackColor = Color.MistyRose
txtUsername.Text = ""
txtPassword.Text = ""
ProgressBar1.Value = 0
End Try
End Sub
And the second button, once logged in, you should be able to search for a patient using this button and choosing a patient from a listbox...
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
If LoggedInToAdastra = False Then
MsgBox("Please re-login to Adastra")
End If
strPatientNHS = lstPatients.SelectedItems(0).SubItems(0).Text
EditNote(strPatientNHS)
End Sub
Public Sub EditNote(strPatientNHS As String)
'Try
doc = WebBrowser1.Document
WebBrowser1.ScriptErrorsSuppressed = True
WebBrowser1.Document.OpenNew(True)
WebBrowser1.Navigate("https://nww.awv.nems.nhs.uk/AWA/login.aspx?ReturnUrl=%2fAWA%2fdefault.aspx")
ProgressBar1.Value = 10
WaitForPageLoad()
ProgressBar1.Value = 20
WebBrowser1.Document.All("ctl00$MainContent$txtUserName").SetAttribute("value", strUsername)
WebBrowser1.Document.All("ctl00$MainContent$txtPassWord").SetAttribute("value", strPassword)
WebBrowser1.Document.All("ctl00$MainContent$btnLogin").InvokeMember("click")
'WebBrowser1.Navigate("https://nww.awv.nems.nhs.uk/AWA/MainMenu.aspx")
WaitForPageLoad()
ProgressBar1.Value = 30
WebBrowser1.Document.All("ctl00$MainContent$ctl01").InvokeMember("click")
WaitForPageLoad()
ProgressBar1.Value = 40
WebBrowser1.Document.GetElementById("ct100_MainContent_txtNationalNumber").SetAttribute("value", strPatientNHS)
WebBrowser1.Document.GetElementById("ct100_MainContent_cboSurgery2").SetAttribute("value", "All Practices")
WebBrowser1.Document.All("ct100$MainContent$bSearch").InvokeMember("click")
End Sub
It errors here on the EditNote sub
WebBrowser1.Document.GetElementById("ct100_MainContent_txtNationalNumber").SetAttribute("value", strPatientNHS)
WebBrowser1.Document.GetElementById("ct100_MainContent_cboSurgery2").SetAttribute("value", "All Practices")
WebBrowser1.Document.All("ct100$MainContent$bSearch").InvokeMember("click")
I have tried all sorts, but not sure why its bringing through the Error (Object reference not set to an instance of an object.)
The control does exist on the web page, and that is the correct ID for it. I have tried using Document.All and looking for the element too but to no avail.
I did resolve this in the end, in quite bizarre fashion...
so it was giving me an error basically because it couldn't find the control
WebBrowser1.Document.All("ctl00$MainContent$txtUserName")
so as a last resort, I copied and pasted the exact control from the page source and it worked... even though every character was the same...
This fixed my problem anyway. Don't type the control out, copy and paste it! Maybe someone with more knowledge can explain how this works? is there hidden characters in the HTML?