VB.Net SelectedChangeCommitted Throwing Error - vb.net

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

Related

Backgroundworker gives multiple error messages

I have a form with three textboxes in it. In my BackgroundWorker1_DoWork handler I test if any TextBox is empty and launch a MessageBox asking the user to fill in all the TextBoxes. This is done in a Try/Catch block. My problem is two fold. If the TextBoxes aren't filled in the user gets the first MessageBox and then another MessageBox when the Catch exception is thrown...so this would be the second MessageBox the user gets. In my BackGroundWorker1_RunWorkCompleted handler I test if an Exception is thrown. It never acknowledges the error and immediately executes the Else block which will be the third message box the user receives saying "Process complete." The Process Complete should not have been shown.
How do I test if there are any TextBoxes not filled in and if they're not throw 1 MessageBox telling the user to fill in all the TextBoxes? And make my RunWorkerComplete handler acknowledge the ElseIf e.Error IsNot Nothing.
Thank you for your help.
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
BackgroundWorker1.WorkerReportsProgress = True
Try
For Each cntrl As Control In Me.Controls()
If TypeOf cntrl Is TextBox Then
If CType(cntrl, TextBox).Text.Equals(String.Empty) Or (CType(cntrl, TextBox).Text = "") Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
End If
End If
Next
runProgram()
Catch ex As Exception
MessageBox.Show("An error occured while trying to load this application. Please contact Maxine Hammett for assistance " &
vbNewLine & "" & vbNewLine & String.Format("Error: {0}", ex.Message))
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled = True Then
MsgBox(" Operation Cancelled ")
ProgressBar1.Value = 0
ElseIf e.Error IsNot Nothing Then
MsgBox("Error in RunWorkerComplete" & e.Error.Message)
Else
MsgBox(" Process Complete ")
Close()
End If
End Sub
Moved the control checking to the execute button. But now I get errors about the text boxes not having a path (one of the text boxes is a path to folder).
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim launchProgram As Boolean = False
While launchProgram = False
For Each cntrl As Control In Me.Controls()
If TypeOf cntrl Is TextBox Then
If CType(cntrl, TextBox).Text.Equals(String.Empty) Or (CType(cntrl, TextBox).Text = "") Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
launchProgram = False
Else
launchProgram = True
End If
End If
Next
End While
If launchProgram = True Then
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
I suggest that you check a single text box a time and show the message if its empty:
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
For Each cntrl As TextBox In Controls.OfType(Of TextBox)
If String.IsNullOrEmpty(cntrl.Text) Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
Return
Else
cntrl.BackColor = SystemColors.Window
End If
Next
BackgroundWorker1.RunWorkerAsync()
End Sub
Or maybe concatenate the names of the empty text boxes in the For..Each block if you really need to prompt the user this way:
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim sb As New StringBuilder
For Each cntrl As TextBox In Controls.OfType(Of TextBox)
If String.IsNullOrEmpty(cntrl.Text) Then
If sb.Length > 0 Then sb.Append(", ")
sb.Append(cntrl.Name)
cntrl.BackColor = Color.Yellow
Else
cntrl.BackColor = SystemColors.Window
End If
Next
If sb.Length > 0 Then
MessageBox.Show("Please enter value in all fields on form" & sb.ToString())
Controls.OfType(Of TextBox).Where(Function(a) String.IsNullOrEmpty(a.Text)).FirstOrDefault?.Focus()
Return
End If
BackgroundWorker1.RunWorkerAsync()
End Sub
Otherwise, run the worker.
Good luck.

Avoid Existing Items in TextBox

Private Sub BtnMoveItemstoTemplate_Click(sender As Object, e As EventArgs) Handles BtnMoveItemstoTemplate.Click
Try
If LBMessageContents.SelectedItem Is Nothing Then
ShowMessage("Select Some Details to Send a Message")
Else
RTMsgContent.Text = RTMsgContent.Text & LBMessageContents.SelectedItem
End If
Catch ex As Exception
HandleClassException(ex)
End Try
End Sub
I write a code for moving an item from ListBox to RichTextBox.
How to validate if a list item is already exist or not.
As vinayak, said, you can use .contains() to know if the text box contains the string or not
Private Sub BtnMoveItemstoTemplate_Click(sender As Object, e As EventArgs) Handles BtnMoveItemstoTemplate.Click
Try
If LBMessageContents.SelectedItem Is Nothing Then
ShowMessage("Select Some Details to Send a Message")
Else
'check if the item already exists
If RtMsgContent.Text.Contains(LBMessageContents.SelectedItem) then
'do what you want to do if the item already exists. like showing message
MsgBox("Error! This item already exists")
Else
'doesn't already exists, add to the textbox
RTMsgContent.Text = RTMsgContent.Text & LBMessageContents.SelectedItem
End If
End If
Catch ex As Exception
HandleClassException(ex)
End Try
End Sub
I got the solution for my question.
I used the [.contains()] function to validate the text is already exists or not.
Private Sub BtnMoveItemstoTemplate_Click(sender As Object, e As EventArgs) Handles BtnMoveItemstoTemplate.Click
Try
If LBMessageContents.SelectedItem Is Nothing Then
ShowMessage("Select Some Details to Send a Message")
Else
**If RtMsgContent.Text.Contains(LBMessageContents.SelectedItem) then Exit Sub**
RTMsgContent.Text = RTMsgContent.Text & LBMessageContents.SelectedItem
End If
Catch ex As Exception
HandleClassException(ex)
End Try
End Sub

Webbrowser control throws NullReferenceException when navigating

I'm trying to build my first HTML UI with Webbrowser component in VB.Net. I have found this code example on Microsoft site
https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.document(v=vs.110).aspx :
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
Handles Me.Load
WebBrowser1.DocumentText =
"<html><body>Please enter your name:<br/>" &
"<input type='text' name='userName'/><br/>" &
"<a href='http://www.microsoft.com'>continue</a>" &
"</body></html>"
End Sub
Private Sub webBrowser1_Navigating(
ByVal sender As Object, ByVal e As WebBrowserNavigatingEventArgs) _
Handles WebBrowser1.Navigating
Dim document As System.Windows.Forms.HtmlDocument =
WebBrowser1.Document
If document IsNot Nothing And
document.All("userName") IsNot Nothing And
String.IsNullOrEmpty(
document.All("userName").GetAttribute("value")) Then
e.Cancel = True
MsgBox("You must enter your name before you can navigate to " &
e.Url.ToString())
End If
End Sub
When I put it on to the test, most of the time throws exception 'System.NullReferenceException' in this part of the code:
If document IsNot Nothing And
document.All("userName") IsNot Nothing And
String.IsNullOrEmpty(
document.All("userName").GetAttribute("value")) Then
Sometimes it works, but mostly it doesn't work at all. Any idea how to fix this? I'm very new to .Net platform and sorry if there is any miss spelling. Any help is appreciated.
If document is nothing then the other clauses of the If statement will generate exceptions because you are attempting to access properties whilst document is Nothing. You need to rewrite the code like this:
Dim document As System.Windows.Forms.HtmlDocument = WebBrowser1.Document
If document IsNot Nothing Then
If document.All("userName") IsNot Nothing Then
If String.IsNullOrEmpty(document.All("userName").GetAttribute("value")) Then
e.Cancel = True
MsgBox("You must enter your name before you can navigate to " &
e.Url.ToString())
End If
End If
End If

Returning text from backgroundworker

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.

nullreferenceexception in gridview when header is clicked

In my DataGridView selectionChange i have this code, so when the row change the texbox also changes. the code below works, i click the row and it displays right, also when i press up/down arrows. My problem is when I click somwhere in the Header of the grid i have this nullreferenceexception error Object reference not set to an instance of an object.. I don't have idea how to handle it, since i down know what it returns.
Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
Dim index As Integer
index = DataGridView1.CurrentCell.RowIndex '<<<<--problem here when I click the header
If (index <= maxrows - 1) Or (index <> Nothing) Then
TextBox2.Text = DataGridView1.Item(1, index).Value()
TextBox3.Text = DataGridView1.Item(2, index).Value()
TextBox4.Text = DataGridView1.Item(3, index).Value()
End If
End Sub
A null reference is raised whenever you get the RowIndex wherein there is no ROW is selected.
Clicking the header calls SORT and this clears the selection.
This will help you get rid of the nullreference exception
If DatagridView1.SelectedRows.Count = 0 Then
Msgbox "Nothing Selected"
Exit Sub 'Trapping
End If
Code:
Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
If DatagridView1.SelectedRows.Count = 0 Then
Msgbox "Nothing Selected"
Exit Sub 'Trapping
End If
Dim index As Integer
With DataGridView
index = .CurrentRow.RowIndex
If (index <= maxrows - 1) Then
TextBox2.Text = .Item(1, index).Value()
TextBox3.Text = .Item(2, index).Value()
TextBox4.Text = .Item(3, index).Value()
End If
End With
End Sub