VB.NET Read 2 checkboxes status from file - vb.net

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.

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?

Threading doesn't complete the task before ending the thread loop

So I did something similar a while ago, but this is essentially a username checker for a (specific) website, they can load in usernames via text file and it will put it into a list box, now I have the start button and it's meant to check each username. Before, however, it froze the program when they checked, but it worked. I tried making it "threaded" so it didn't freeze.
The problem now is that it doesn't check them all, and finishes instantly.
CODE:
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Button6.Enabled = False
Dim goodUsers As New SaveFileDialog()
goodUsers.Filter = "TXT file (*.txt)|*.txt"
Dim flag As Boolean
Dim Incomplete As Integer = 0
Dim Taken As Integer = 0
Dim sb As New StringBuilder
If goodUsers.ShowDialog() = DialogResult.OK Then
Dim checkerMT As New Thread(
Sub()
For Each i As String In UsernameList.Items
WebRequest.Create("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString)
Dim cResult As String = New System.Net.WebClient().DownloadString("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString).ToString
If cResult = "taken" Then
flag = False
ElseIf cResult = "nottaken" Then
flag = True
End If
If flag = True Then
sb.Append(i & vbNewLine)
Else
Incomplete = Incomplete + 1
Taken = UsernameList.Items.Count - Incomplete
End If
Next
End Sub
)
checkerMT.Start()
Try
File.WriteAllText(goodUsers.FileName, sb.ToString)
Catch ex As Exception
Exit Sub
End Try
End If
MessageBox.Show("Checking available usernames, complete!", "NameSniper Pro")
Button6.Enabled = True
End Sub
You cannot access UI elements (UsernameList.Items) from a thread other than the UI. Instead add a background worker to your form to handle the basic threading stuff (progress reporting, finish reporting, exception handling). Pass into this an object that contains the settings your job needs to do its work without interacting with the ui.
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Button6.Enabled = False
Dim goodUsers As New SaveFileDialog()
goodUsers.Filter = "TXT file (*.txt)|*.txt"
If goodUsers.ShowDialog() = DialogResult.OK Then
'Note: You'll need to add the filenames
BackgroundWorker1.RunWorkerAsync(New State() With {.Names = {}, .FileName = goodUsers.FileName})
End If
End Sub
Class State
Public Names As List(Of String)
Public StringBuilder As New System.Text.StringBuilder
Public Incomplete As Integer
Public Taken As Integer
Public FileName As String
End Class
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim state = CType(e.Argument, State)
For Each i As String In state.Names
Using cli = New System.Net.WebClient()
Dim cResult = cli.DownloadString("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString).ToString
If cResult = "nottaken" Then
state.StringBuilder.Append(i & vbNewLine)
Else
state.Incomplete = state.Incomplete + 1
state.Taken = state.Names.Count - state.Incomplete
End If
End Using
Next
IO.File.WriteAllText(state.FileName, state.StringBuilder.ToString)
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Error IsNot Nothing Then
MessageBox.Show(e.Error.ToString(), "Error")
Else
MessageBox.Show("Checking available usernames, complete!", "NameSniper Pro")
End If
Button6.Enabled = True
End Sub
The SaveFileDialog can be used as "Using directive"
Why do you create a webrequest on the one hand, and on the other hand use a webclient? That does not make sense at all.
Instead of your strange if condition, write:
flag = (cResult.Equals("nottaken"))
All code you want to run after the actions you are currently running in your thread have to be in your thread as well, because it is async.
You have to invoke if you use user controls within a thread
and so on..
Please turn Option Strict On and Option Infer Off
There are lots of other things you could do better.
Please remove the webrequest and webclient combination yourself, that does not make sense at all.
Take a look at this, I cleared it a little bit:
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim Incomplete As Integer = 0
Dim Taken As Integer = 0
Dim sb As New StringBuilder
Using goodUsers As SaveFileDialog = new SaveFileDialog()
goodUsers.Filter = "TXT file (*.txt)|*.txt"
If not goodUsers.ShowDialog() = DialogResult.OK Then Exit Sub
Dim checkerMT As New Thread(
Sub()
Me.invoke(sub()
Button6.Enabled = False
For Each i As String In UsernameList.Items
WebRequest.Create("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString)
Dim cResult As String = New System.Net.WebClient().DownloadString("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString).ToString
If (cResult.toLower().Equals("nottaken")) Then
sb.Append(String.Concat(i , Environment.NewLine)
Else
Incomplete += 1
Taken = UsernameList.Items.Count - Incomplete
End If
Next
File.WriteAllText(goodUsers.FileName, sb.ToString)
Button6.Enabled = True
MessageBox.Show("Checking available usernames, complete!", "NameSniper Pro")
End Sub)
End Sub
)
checkerMT.IsBackground = True;
checkerMT.Start()
End Sub

Visual basic If and else not working 2015

I am a newbie and I am facing some problem with the 'if' and 'else' function of visual basic.
I have added a button labeled as Save, its code is as given below:
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
If CheckBox1.Checked = True Then
Dim savedata7 As New System.IO.StreamWriter("dat0C.bin")
savedata7.WriteLine("checked")
savedata7.Close()
End If
If CheckBox1.Checked = False Then
Dim savedata7 As New System.IO.StreamWriter("dat0C.bin")
savedata7.WriteLine("unchecked")
savedata7.Close()
End If
If CheckBox2.Checked = True Then
Dim savedata8 As New System.IO.StreamWriter("dat1C.bin")
savedata8.WriteLine("checked")
savedata8.Close()
End If
If CheckBox2.Checked = False Then
Dim savedata8 As New System.IO.StreamWriter("dat1C.bin")
savedata8.WriteLine("unchecked")
savedata8.Close()
End If
End Sub
And another button labeled Load, its code is given below:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim dataloader As New System.IO.StreamReader("dat0C.bin")
Label17.Text = dataloader.ReadToEnd
dataloader.Close()
Catch ex As Exception
End Try
Try
Dim dataloader As New System.IO.StreamReader("dat1C.bin")
label10.Text = dataloader.ReadToEnd
dataloader.Close()
Catch ex As Exception
End Try
If Label17.Text = "checked" Then
CheckBox1.Checked = True
Else
CheckBox1.Checked = False
End If
If Label10.Text = "checked" Then
CheckBox2.Checked = True
Else
CheckBox1.Checked = False
End If
End Sub
The Save button(Button5) is working perfectly fine, but the Load button(Button1) is not working as it should, on clicking Button1 the files 'dat0C.bin' and 'dat1c.bin' are loaded in 'Label17' and 'Label10' respectively but it is not working(i.e. it is not Checking the CheckBoxes1 or 2) from
If Label17.Text = "checked" Then
CheckBox1.Checked = True
Else
CheckBox1.Checked = False
End If
If Label10.Text = "checked" Then
CheckBox2.Checked = True
Else
CheckBox1.Checked = False
End If
Please correct me, If I'm doing anything wrong in it.
This happens because in the reading code you use ReadToEnd instead of ReadLine.
This method reads back the newline character added by WriteLine and doesn't strip it away as ReadLine
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Using dataloader = New System.IO.StreamReader("dat0C.bin")
Label17.Text = dataloader.ReadLine()
End Using
Catch ex As Exception
MessageBox.Show("Exception=" & ex.Message)
End Try
....
A part from this you really should put the creation of disposable objects like the reader and the write inside a using statement to be sure that these objects are properly closed and disposed ALSO in case of exceptions.
Said that, your code could be simplified a lot if you use the static methods of the File class
WRITING
File.WriteAllText("dat0C.bin", If(CheckBox1.Checked, "checked", "unchecked"))
File.WriteAllText("dat1C.bin", If(CheckBox2.Checked, "checked", "unchecked"))
READING
Label17.Text = File.ReadAllText("dat0C.bin")
Label10.Text = File.ReadAllText("dat1C.bin")
CheckBox1.Checked = (Label17.Text = "checked")
CheckBox2.Checked = (Label10.Text = "checked")
Asside from not naming your controls, and not disposing properly of your StreamReader or StreamWriter instances the reason this is not working correctly is because when you write your file you call WriteLine - which appends a carriage return and line feed onto the end of what you've written.
You then read the file, and put the content in a label, which itself will render the CR/LF albeit not visible to you. You then compare to the Text of this label but without the CR/LF - so that comparison evaluates false.

Null Reference Exception Run Time Error

Hi all im getting a null reference run time error with one line of code in my project, however if i break point it and then step through it everything works fine. Any Thoughts
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim checkbox_l As String = "CheckBox"
Dim checkbox_i As string
For i As Integer = 1 To id Step 1
checkbox_i = checkbox_l + i.ToString
Try
If CType(Panel1.Controls(checkbox_i), CheckBox).Checked = True Then
My.Settings.name = Panel1.Controls("CheckBox" & i).Text
Call installer_properties()
Call start_install()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Next
End Sub
The code is meant to check if a dynamically created checkbox has been checked and then move on accordingly, however im getting an error with the line
If CType(Panel1.Controls(checkbox_i), CheckBox).Checked = True Then
Use Debug.Assert to catch it
Dim c as Control = Panel1.Controls(checkbox_i)
Debug.Assert(c IsNot Nothing)
Dim cb as CheckBox = TryCast(c, CheckBox)
If cb isNot Nothing Then
If cb.Checked = True Then
My.Settings.name = cb.Text
Call installer_properties()
Call start_install()
End If
End If
To get result 1 if checked and 0 - if not, you can write down:
textbox1.text = Microsoft.VisualBasic.Right(Panel1.Controls("CheckBox" & i).ToString, 1)

VB.NET Process Redirect Output Not Working

I'm trying to redirect the output from a command-line application in VB.NET, and for some reason it fails to redirect the output. Here's my code:
Dim myProcess As Process = New Process
myProcess.StartInfo.FileName = "g++"
myProcess.StartInfo.Arguments = CMDLineCommand
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.StartInfo.CreateNoWindow = True
myProcess.Start()
Dim output As String = myProcess.StandardOutput.ReadToEnd
myProcess.WaitForExit()
CMDLineOutputTextBox.Text = output
Does anybody know why it's not being redirected? Thanks in advance!
-Neil
EDIT: Here's my full code, in case there's anything weird with my syntax:
Dim myProcess As Process = New Process
myProcess.StartInfo.FileName = "g++"
myProcess.StartInfo.Arguments = CMDLineCommand
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.StartInfo.CreateNoWindow = True
myProcess.EnableRaisingEvents = True
AddHandler myProcess.OutputDataReceived, AddressOf GotData
myProcess.Start()
CMDLineOutputTextBox.Text = ""
myProcess.BeginOutputReadLine()
Later on...
Private Sub GotData(sendingProcess As Object, outLine As DataReceivedEventArgs)
If Not String.IsNullOrEmpty(outLine.Data) Then
SetText(outLine.Data)
End If
End Sub
Delegate Sub SetTextCallback(value As String)
Private Sub SetText(ByVal value As String)
If Me.CMDLineOutputTextBox.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {value})
Else
Me.CMDLineOutputTextBox.Text += value + Environment.NewLine
End If
End Sub
Anything weird?
Your method will work, provided by the time you hit the line where you read the output to the end, all of the output is there. Since you are using g++, I assume that may not always be the case. You will probably be better off using the OutputDataReceived Event and capturing the data from that.
Dim myProcess As Process = New Process
myProcess.StartInfo.FileName = "ping"
myProcess.StartInfo.Arguments = "www.google.com"
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.StartInfo.CreateNoWindow = True
myProcess.EnableRaisingEvents = True
AddHandler myProcess.OutputDataReceived, AddressOf GotData
myProcess.Start()
myProcess.BeginOutputReadLine()
Then you handle the event like this:
Private Sub GotData(sendingProcess As Object, outLine As DataReceivedEventArgs)
If Not String.IsNullOrEmpty(outLine.Data) Then
SetText(outLine.Data)
End If
End Sub
Delegate Sub SetTextCallback(value As String)
Private Sub SetText(ByVal value As String)
If Me.TextBox3.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {value})
Else
Me.TextBox3.Text += value + Environment.NewLine
End If
End Sub
I have noticed the waitforExit seems to make the code lock during the invoke.required check. When I take out the waitforexit it works.