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?
Related
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
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.
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?
I am making a TicTacToe Program in Vb.net and it is essentially 9 games into one "big" game. So I have 81 buttons I want to disable able the winner is determined. How can I address them all in the shortest amount of code?
Private Sub CheckOverallWinner()
If humangame1 = 1 And humangame2 = 1 And humangame3 = 1 Then
MsgBox("Human Wins")
Button1.Enabled = False
Button2.Enabled = False
Button3.Enabled = False
Button4.Enabled = False
Button5.Enabled = False
Button6.Enabled = False
Button7.Enabled = False
Button8.Enabled = False
Button9.Enabled = False
End If
End Sub
So instead of writing Button_.Enabled = False all the way through 81 is there a shorter way? Thanks!
Dim o As Object
For Each o In Me.Controls
If TypeOf o Is Button Then
o.Enabled = False
End If
Next
Just tried this in VS2008
Another option using Controls.Find(). This will work no matter where the buttons are contained, even if they are in multiple containers:
Private Sub Foo()
SetButtonsState(False)
End Sub
Private Sub SetButtonsState(ByVal state As Boolean)
Dim matches() As Control
For i As Integer = 1 To 81
matches = Me.Controls.Find("Button" & i, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is Button Then
Dim btn As Button = DirectCast(matches(0), Button)
btn.Enabled = state
End If
Next
End Sub
I am looking for a way, if its even possible, to re enable a label without actually needing to use its label name?
I have a game with labels I am using as click able boxes. The first box becomes disabled after the click event occurs, I want after the second box is clicked to re enable that first box. Any Ideas? Here is the code for the first two box click events.
Edit: there will be 15 labels, 2 can be chosen at a time. The first will be disabled so that it can't be chosen a second time.
Private Sub lblMemory1_Click(sender As Object, e As EventArgs) Handles lblMemory1.Click
Dim intClickBox As Integer = 1
Dim intClickAnswer As Integer
intClickAnswer = GuessClick(intClickBox)
If blnActive = False Then
blnActive = True
whatClicked1 = intClickBox
lblMemory1.BackColor = Color.Green
lblMemory1.Text = intClickAnswer.ToString
lblMemory1.Refresh()
System.Threading.Thread.Sleep(2000)
lblMemory1.BackColor = Color.Cyan
lblMemory1.Text = "X"
lblMemory1.Enabled = False
End If
If blnActive = True Then
whatClicked2 = intClickBox
lblMemory1.BackColor = Color.Green
lblMemory1.Text = intClickAnswer.ToString
lblMemory1.Refresh()
System.Threading.Thread.Sleep(2000)
lblMemory1.BackColor = Color.Cyan
lblMemory1.Text = "X"
blnActive = False
End If
End Sub
Private Sub lblMemory2_Click(sender As Object, e As EventArgs) Handles lblMemory2.Click
Dim intClickBox As Integer = 2
Dim intClickAnswer As Integer
intClickAnswer = GuessClick(intClickBox)
If blnActive = False Then
blnActive = True
whatClicked1 = intClickBox
lblMemory2.BackColor = Color.Green
lblMemory2.Text = intClickAnswer.ToString
lblMemory2.Refresh()
System.Threading.Thread.Sleep(2000)
lblMemory2.BackColor = Color.Cyan
lblMemory2.Text = "X"
lblMemory2.Enabled = False
End If
If blnActive = True Then
whatClicked2 = intClickBox
lblMemory2.BackColor = Color.Green
lblMemory2.Text = intClickAnswer.ToString
lblMemory2.Refresh()
System.Threading.Thread.Sleep(2000)
lblMemory2.BackColor = Color.Cyan
lblMemory2.Text = "X"
blnActive = False
End If
End Sub
you can do something like
Public Sub game(sender As Object)
Dim lbl As Label = sender
If lbl.Enabled Then
For i = 0 To Me.Controls.Count - 1
Dim lbl2 As Label = Me.Controls(i)
If Not (lbl2.Enabled) Then
lbl2.Enabled = True
GoTo exitLoop
End If
Next
End If
exitLoop:
lbl.Enabled = False
End Sub
then in each label just call the game sub and pass sender like so...
Private Sub Label1_Click(sender As System.Object, e As System.EventArgs) Handles Label1.Click
game(sender)
End Sub
this will allow only 1 label to be diabled at any give time...
you can also (within the loops) use lbl and lbl2 to set the properties for each label.
if you use a var to save the name of the first textbox you can also specifically re-enable only that box...
let me know if you want the code for that too.