I am trying to display results from my backgroundworker into a textbox. I looked online, and it seems like I am using the right code, but its nothing doing anything.
Code:
Do While sr.Peek <> -1
line = sr.ReadLine()
BackgroundWorker1.ReportProgress(30, "Searching Log: Started")
If line.TrimStart(trimchars).StartsWith(TDate.Text) And line.Trim(trimchars).Contains("[Log Number:") Then
' found pattern
BackgroundWorker1.ReportProgress(40, "Searching Log: Complete")
'SN.Text = line
e.Result = line
NoteLab.Visible = False
ElseIf line.TrimStart(trimchars).StartsWith(Ydate.Text) And line.Trim(trimchars).Contains("[Log Number:") Then
BackgroundWorker1.ReportProgress(50, "Searching Log: Failed - Searching for yesterdays")
'SN.Text = line
e.Result = line
NoteLab.Visible = True
BackgroundWorker1.ReportProgress(60, "Searching Log: Complete")
'
End If
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
SN.Text = e.Result
End Sub
Error:
There is NO error. It just does NOT put anything into the textbox.
I think that should be all information needed. Thanks in advance for any help.
Related
Hello again StackOverflow Community!
I am having some issues with a BackgroundWorker and AsyncCancel. The BackgroundWorker simply sends a email but I would like to be able to report when the task or email has been sent and as well be able to cancel the task or email from being sent.
The problem is after hitting cancel, it continues and then reports a error, not canceled.
Any help is greatly appreciated!
Thank you!
Here is my complete code minus comments and imports:
Private Sub Sendmail_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
StatusLabel.Text &= "Idle"
End Sub
Private Sub SendmailBackgroundWorker_DoWork(sender As Object, e As DoWorkEventArgs) Handles SendmailBackgroundWorker.DoWork
Try
Dim Smtp As New SmtpClient()
Dim Email As New MailMessage()
Smtp.Port = 25
Smtp.Host = "mail.server.com"
Smtp.EnableSsl = False
Smtp.UseDefaultCredentials = False
Smtp.Credentials = New Net.NetworkCredential("user#server.com", "password")
Email = New MailMessage()
Email.From = New MailAddress(FromTextBox.Text)
Email.To.Add(ToTextBox.Text)
Email.Subject = SubjectTextBox.Text
Email.IsBodyHtml = False
Email.Body = BodyTextBox.Text
Smtp.Send(Email)
Catch ex As Exception
MsgBox("Sendmail Error!" & vbNewLine & vbNewLine & ex.ToString)
End Try
If SendmailBackgroundWorker.CancellationPending Then
StatusLabel.Text = "Canceling"
e.Cancel = True
End If
End Sub
Private Sub SendmailBackgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles SendmailBackgroundWorker.RunWorkerCompleted
StatusLabel.Text = "Status: "
If (e.Error IsNot Nothing) Then
StatusLabel.Text &= "Worker Error!" & vbNewLine & vbNewLine & e.Error.Message
ElseIf e.Cancelled Then
StatusLabel.Text &= "Canceled!"
Else
StatusLabel.Text &= "Sent!"
End If
SendButton.Enabled = True
CancelButton.Enabled = False
End Sub
Private Sub SendButton_Click(sender As Object, e As EventArgs) Handles SendButton.Click
StatusLabel.Text = "Status: "
SendButton.Enabled = False
CancelButton.Enabled = True
SendmailBackgroundWorker.WorkerSupportsCancellation = True
SendmailBackgroundWorker.WorkerReportsProgress = True
StatusLabel.Text &= "Sending..."
SendmailBackgroundWorker.RunWorkerAsync()
End Sub
Private Sub CancelButton_Click(sender As Object, e As EventArgs) Handles CancelButton.Click
CancelButton.Enabled = False
SendmailBackgroundWorker.CancelAsync()
End Sub
That is working exactly as it should. The problem is that you haven't read up properly on how it works. Calling CancelAsync (NOT AsyncCancel) on a BackgroundWorker does NOT cancel anything. All it does is set a flag on the BackgroundWorker object. It's up to you to test that flag in your DoWork event handler and, if it's set, it's then for you to stop the work. In your current code, you're not testing that flag until after the email has been sent so of course the email gets sent whether you try to cancel or not.
You are overestimating what cancelling a BackgroundWorker can accomplish. The BackgroundWorker itself doesn't know what you're doing in the DoWork event handler so it's not going to simply abort it. It gives you the chance to terminate the task at an appropriate point in the code. If there is no appropriate point then you can't cancel anything.
In your case, once you call Send on your SmtpClient, you can't do anything until that synchronous method returns, so you can't cancel it. What you should be doing is not using a BackgroundWorker at all but rather the asynchronous functionality built into the SmtpClient class. It has a SendAsync method and a SendAsyncCancel method, so you can let it handle the multithreading for you.
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.
I am really annoyed here. I don't understand why this event keeps throwing a blank error. Below is my code.
Private Sub cboSections_SelectedChangeCommitted(sender As System.Object, e As System.EventArgs) Handles cboSections.SelectionChangeCommitted
On Error GoTo EH
If TypeOf sender Is Windows.Forms.ComboBox Then
'some boolean that checks if we are skipping this event, thus it does if so
If mbSkipEvent Then Exit Sub
'checks if index that was changed to is > 0 then it toggles the bottom command buttons
If cboSections.SelectedIndex > 0 Then
ToggleCmdButtons(True)
Else
ToggleCmdButtons(False)
End If
'sets the string msPurpose
msPurpose = "Show Section"
Debug.Print("Im here")
End If
EH:
Debug.Print("Error Description: " & Err.Description)
End Sub
In my output I get "Error Description: ". Thats it. If anyone has any solution or point in the right direction that would be great.
Let's try some real error handling and see if you get anything better. While we're at it, we can simplify the code a bit:
Private Sub cboSections_SelectedChangeCommitted(sender As System.Object, e As System.EventArgs) Handles cboSections.SelectionChangeCommitted
Dim comboBox = TryCast(sender, ComboBox)
If comboBox Is Nothing OrElse mbSkipEvent Then Exit Sub
Try
'checks if index that was changed to is > 0 then it toggles the bottom command buttons
ToggleCmdButtons(cboSections.SelectedIndex > 0)
'sets the string msPurpose
msPurpose = "Show Section"
Debug.Print("Im here")
Catch Ex As Exception
Debug.Print("Error Description: " & Ex.Message)
End Try
End Sub
It keeps returning null and I was hoping someone could clean it up for me and see if there is a simpler way to do this. I'm really wanting to start making my game.
Public Class frmLogin
Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click
Application.Exit()
End Sub
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
Dim FILE_NAME As String = "C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtCUser.Text
If File.Exists(FILE_NAME) Then
Me.lblExists.Text = "Username has already been created!"
Return
End If
If txtCUser.Text.Length < 3 Then
Me.lblExists.Text = "Must have atleast 3 characters."
Return
End If
Dim writeFile As StreamWriter = File.CreateText("C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtCUser.Text)
writeFile.WriteLine("User: " + Me.txtCUser.Text) ' user
writeFile.WriteLine("Pass: " + Me.txtCPass.Text) ' pass
writeFile.WriteLine("-------------------")
writeFile.Close()
End Sub
Private Function GetLine(ByVal fileName As String, ByVal line As Integer) As String
Try
If File.Exists(fileName) = False Then
Using sr As New StreamReader("C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtUser.Text)
For i As Integer = 1 To line - 1
sr.ReadLine()
Next
Return (sr.ReadLine())
sr.Close()
End Using
End If
Catch ex As Exception
Return ex.Message
End Try
End Function
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim FILE_NAME As String = "C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtUser.Text
If File.Exists(FILE_NAME) And Me.txtPassword.Text = (GetLine(FILE_NAME, 2).Substring(6)) Then
Me.lblLoggedIn.Text = "Logged"
ElseIf File.Exists(FILE_NAME) = False Then
Me.lblLoggedIn.Text = "You must create an account! Navigate to TabPage2."
End If
End Sub
End Class
It would really help a lot. I just started vb not to long ago maybe about a week or two.
Three things. First, in GetLine() you're attempting to open the file if it does NOT exist; change from False to True. Second, you should open the file name that was passed in, not a hard-coded one that uses the value from a TextBox. Lastly, to get rid of the warning, you need to return something if the file does not exist:
Change GetLine() to:
Private Function GetLine(ByVal fileName As String, ByVal line As Integer) As String
Try
If File.Exists(fileName) Then
Using sr As New StreamReader(fileName)
For i As Integer = 1 To line - 1
sr.ReadLine()
Next
Return sr.ReadLine()
End Using
Else
Return "{File Not Found: " & fileName & "}"
End If
Catch ex As Exception
Return ex.Message
End Try
End Function
*You were returning the exception as a string, so I followed that model with the file not found error. How will you know, though, if you have an actual error, or if the line in the file was exactly like the "error" being returned?
I'm trying to read a text file with multiple lines and then display it in a textbox. The problem is that my program only reads one line. Can someone point out the mistake to me?
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private BagelStreamReader As StreamReader
Private PhoneStreamWriter As StreamWriter
Dim ResponseDialogResult As DialogResult
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
'Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
'Is file already open
If PhoneStreamWriter IsNot Nothing Then
PhoneStreamWriter.Close()
End If
With OpenFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
'If ResponseDialogResult <> DialogResult.Cancel Then
' PhoneStreamWriter = New StreamWriter(OpenFileDialog1.FileName)
'End If
Try
BagelStreamReader = New StreamReader(OpenFileDialog1.FileName)
DisplayRecord()
Catch ex As Exception
MessageBox.Show("File not found or is invalid.", "Data Error")
End Try
End Sub
Private Sub DisplayRecord()
Do Until BagelStreamReader.Peek = -1
TextBox1.Text = BagelStreamReader.ReadLine()
Loop
'MessageBox.Show("No more records to display.", "End of File")
'End If
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
With SaveFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
PhoneStreamWriter.WriteLine(TextBox1.Text)
With TextBox1
.Clear()
.Focus()
End With
TextBox1.Clear()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
PhoneStreamWriter.Close()
Me.Close()
End Sub
End Class
Here is a sample textfile:
Banana nut
Blueberry
Cinnamon
Egg
Plain
Poppy Seed
Pumpkin
Rye
Salt
Sesame seed
You're probably only getting the last line in the file, right? Your code sets TextBox1.Text equal to BagelSteramReader.ReadLine() every time, overwriting the previous value of TextBox1.Text. Try TextBox1.Text += BagelStreamReader.ReadLine() + '\n'
Edit: Though I must steal agree with Hans Passant's commented idea on this; If you want an more efficient algorithm, File.ReadAllLines() even saves you time and money...though I didn't know of it myself. Darn .NET, having so many features...
I wrote a program to both write to and read from a text file. To write the lines of a list box to a text file I used the following code:
Private Sub txtWriteToTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtWriteToTextfile.Click
Dim FileWriter As StreamWriter
FileWriter = New StreamWriter(FileName, False)
' 3. Write some sample data to the file.
For i = 1 To lstNamesList.Items.Count
FileWriter.Write(lstNamesList.Items(i - 1).ToString)
FileWriter.Write(Chr(32))
Next i
FileWriter.Close()
End Sub
And to read and write the contents of the text file and write to a multi-line text box (you just need to set the multiple lines property of a text box to true) I used the following code. I also had to do some extra coding to break the individual words from the long string I received from the text file.
Private Sub cmdReadFromTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadFromTextfile.Click
Dim sStringFromFile As String = ""
Dim sTextString As String = ""
Dim iWordStartingPossition As Integer = 0
Dim iWordEndingPossition As Integer = 0
Dim iClearedTestLength As Integer = 0
Dim FileReader As StreamReader
FileReader = New StreamReader(FileName)
sStringFromFile = FileReader.ReadToEnd()
sTextString = sStringFromFile
txtTextFromFile.Text = ""
Do Until iClearedTestLength = Len(sTextString)
iWordEndingPossition = CInt(InStr((Microsoft.VisualBasic.Right(sTextString, Len(sTextString) - iWordStartingPossition)), " "))
txtTextFromFile.Text = txtTextFromFile.Text & (Microsoft.VisualBasic.Mid(sTextString, iWordStartingPossition + 1, iWordEndingPossition)) & vbCrLf
iWordStartingPossition = iWordStartingPossition + iWordEndingPossition
iClearedTestLength = iClearedTestLength + iWordEndingPossition
Loop
FileReader.Close()
End Sub