Can not find out why 'NullReference Exception' is thorwn - vb.net

I have a Telerik Tabbed PageView in my Windows Form application which I can edit tab's titles by double clicking on them which initiates a text editor. Following subs are taking care of altered labels - check the edited labels not to be blank:
Private Sub ViewElement_EditorInitialized(sender As Object, e As UI.RadPageViewEditorEventArgs)
AddHandler MountingSystemTabControl.ViewElement.ActiveEditor.Validating, AddressOf ActiveEditor_Validating
AddHandler MountingSystemTabControl.ViewElement.ActiveEditor.Validated, AddressOf ActiveEditor_Validated
AddHandler MountingSystemTabControl.ViewElement.ActiveEditor.ValidationError, AddressOf ActiveEditor_ValidationError
End Sub
Private Sub ActiveEditor_Validating(sender As Object, e As CancelEventArgs)
Dim editor As UI.RadPageViewElement.PageViewItemTextEditor = TryCast(sender, UI.RadPageViewElement.PageViewItemTextEditor)
If editor IsNot Nothing AndAlso MountingSystemTabControl.ViewElement.ActiveEditor.Value = String.Empty Then
e.Cancel = True
End If
End Sub
Private Sub ActiveEditor_ValidationError(sender As Object, e As UI.ValidationErrorEventArgs)
RadMessageBox.Show("Array label can't be empty!", "Error", MessageBoxButtons.OK, RadMessageIcon.[Error])
End Sub
Private Sub ActiveEditor_Validated(sender As Object, e As EventArgs)
RadMessageBox.Show("Array label has been successfully updated!", "Information", MessageBoxButtons.OK, RadMessageIcon.Info)
End Sub
Moreover, this line is there in my Form_Load event:
AddHandler MountingSystemTabControl.ViewElement.EditorInitialized, AddressOf ViewElement_EditorInitialized
Now the problem is, whenever I run the code, after the MessageBox shows me the "Array label has been successfully updated!" message, a NullReference Exception is thrown which it seems I can't catch it not even with Application Event handlers ! After breaking the code, Visual Studio refers me to this line as the source of the exception:
RadMessageBox.Show("Array label has been successfully updated!", "Information", MessageBoxButtons.OK, RadMessageIcon.Info)
And that's what confuses me because I can't find anything referenced in that line (of course there is something but I don't know what).
Call Stack screenshot
Main idea of the code.

As memory serves...I think RadMessageBox calls for a Parent argument.
Try this:
RadMessageBox.Show(Me, "Array label has been successfully updated!", "Information", MessageBoxButtons.OK, RadMessageIcon.Info)

The issue was addressed by updating to 'Telerik UI for WinForms Q1 2015 (version 2015.1.225)'

Related

vb.net / C# External handler

I have a form used to display options about processes.
When options are applyed :
frmOptions
For Each ltvi As ListViewItem In ltvProcesses.CheckedItems
Dim proc As Process = CType(ltvi.Tag, Process)
targeted_processes.Add(proc)
AddHandler proc.Exited, AddressOf frmAET.a_target_process_has_been_exited
proc.EnableRaisingEvents = True
Next
And in a tools module :
Public Sub a_target_process_has_been_exited(sender As Object, e As EventArgs)
frmAET.btnStatus.ForeColor = Color.Red
msgbox("OK")
End Sub
And... the messagebox displays its message but the color doesn't change.
After some tries, the problem is when a_target_process_has_been_exited is actived by the handler.
If I do this (Button1 belongs to frmAET, like btnStatus) :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
a_target_process_has_been_exited()
End Sub
It works ! But not when I really want (when a process is ended).
So, the problem is when the sub is called by the process end event.
And when I try to specify this (maybe a frmAET's sub can modify its controls) :
AddHandler leproc.Exited, AddressOf frmAET.a_target_process_has_been_exited
Error : Reference to a non-shared member requires an objet reference
Could you help me ?
Your AddHandler seems to use AddressOf frmAET.a_target_process_has_been_exited, that means method in frmAET form itself. Not tools module as you stated.
Let's consider your frmOptions is correct and frmAET is containing this (with removed explicit reference to frmAET, since it's local)
Public Sub a_target_process_has_been_exited(sender As Object, e As EventArgs)
btnStatus.ForeColor = Color.Red
MsgBox("OK")
End Sub
As comments already explained, your event handler is called in another thread and you need to sync yourself to main UI thread. For example like this:
Public Sub a_target_process_has_been_exited(sender As Object, e As EventArgs)
Me.BeginInvoke(Sub() HandleProcessExit())
End Sub
Public Sub HandleProcessExit
btnStatus.ForeColor = Color.Red
MsgBox("OK")
End Sub
This version will block main UI thread until you click on the MsgBox button.
You should add some Try/Catch block. Exception in another threads are difficult to detect otherwise.
This code depends on implicit form instances that VB.NET creates for you. I expect your frmAET is actually My.Forms.frmAET instance to make this work.

Show MessageBox modaly from background thread

In my Winform VB.NET application I am checking some fields. In case that one particular field is equal to true I need to show message. Normally it would be like this:
If (myField) Then
MessageBox.Show("Something is wrong", "Warning", MessageBoxButtons.OK)
// continuing...
End If
This message must be shown modaly (user can return to main form only after clicking OK button). Problem is that I do not want the thread to wait for the clicking (just show the message and continue - do not wait for OK button).
My only idea is to show the message in background thread:
If (myField) Then
Dim t As Thread = New Thread(AddressOf ShowMyMessage)
t.Start()
// continuing...
End If
Private Sub ShowMyMessage()
MessageBox.Show("Something is wrong", "Warning", MessageBoxButtons.OK)
End Sub
But in this case the message is not shown modaly (user can return to main form and interact with it without clicking Ok button).
Any ideas?
Your design is likely to be wrong if this is what you want to do, but for an exercise I wrote something that should achieve what you want.
Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
Dim thr As New Thread(Sub() ThreadTest())
thr.Start()
End Sub
Private Sub ThreadTest()
Debug.WriteLine("Started")
Me.ShowMessageBox("Can't click on the main form now", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Debug.WriteLine("Thread continued")
End Sub
Public Sub ShowMessageBox(textToShow As String, caption As String, buttons As MessageBoxButtons, icon As MessageBoxIcon)
Me.BeginInvoke(Sub() MessageBox.Show(textToShow, caption, buttons, icon))
End Sub
When you run it you will see that the ThreadTest code carries on past the showing of the messagebox, but no interaction is allowed with the main form until the ok is clicked on the message box

Cant load image in context menu as icon

I am trying to use the code from the following link:
VB- Helper Create menu items at run time with images, shortcut keys, and event handlers in Visual Basic .NET
The only difference is that I want a local image and not one from my.Recources
What I have is the following:
''Tool 2 displays a string and image.
Dim tool2 As New ToolStripMenuItem("Tool 2", (Image.FromFile("C:\test\icon.jpg")))
tool2.Name = "mnuToolsTool2"
tool2.ShortcutKeys = (Keys.D2 Or Keys.Control) ' Ctrl+2
AddHandler tool2.Click, AddressOf mnuTool2_Click
ToolStripMenuItem1.DropDownItems.Add(tool2)
I could not reproduce this "error". However, from the given text, code and link, my best guess is as follows:
You are using a 64 bit machine.
You run the code inside the Form.Load event.
An error occurs somewhere in this method.
Private Sub _Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Code...
Throw New Exception("ooops..")
'Code...
End Sub
As you might not know is that errors thrown in the Form.Load on a 64 bit machine are "swallowed" by the system.
For more information, read this SO post: Why the form load can't catch exception?
You should move your code inside the constructor:
Public Sub New()
Me.InitializeComponent()
'Code goes here...
End Sub
Or change to the Form.Shown event:
Private Sub _Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
Try
'Code goes here...
Catch ex As Exception
MessageBox.Show(ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub

Make error window

I want to create my edition error report form instead default error window.
How I can create my edition form error report?
For example:
So you want to call a custom handler when exception happens? No problem, just define these 3 magic lines in the beginning of your program (as first lines of Sub Main):
AddHandler Application.ThreadException, AddressOf GenericHandler
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledHandler
Then define GenericHandler and UnhandledHandler, which would call your custom form.
Here is a sample implementation of both handlers:
Public Shared Sub GenericHandler(ByVal sender As Object, ByVal args As Threading.ThreadExceptionEventArgs)
ReportException(args.Exception)
End Sub
Public Shared Sub UnhandledHandler(ByVal sender As Object, ByVal args As UnhandledExceptionEventArgs)
If Not Debugger.IsAttached Then
ReportException(args.ExceptionObject)
End
End If
Public Shared Sub ReportException(ByVal ex As System.Exception)
MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Unhandled exception - Please contact support")
'you can further improve this to add custom logging etc.
End Sub

Application.Exit() and FormClosing event in Vb.net

I have a single windows form application that is running in system tray icon.If the user press X button of the windows form a messagebox is displayed with Yes and No ( Yes ->close the form---No->keep the form running in system tray icon).
I was thinking to prevent the scenario when the user open another instance of the application when there is already an instance running so i have used this code :
If Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length> 1 Then
MessageBox.Show("Another instance is running", "Error Window", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
Application.Exit()
End If
The problem is that when i want to test this the message is displayed but after i press ok, a new messagebox appears (that one from Private Sub Form_FormClosing ).If i choose NO i will have to instance running!
I have read that Application.Exit fires the Form_FormClosing event.
Is there any possibility to cancel the triggering of the Form_FormClosing event,or am i doing something wrong?
'this is the formclosing procedure
Private Sub Form_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Try
Dim response As MsgBoxResult
response = MsgBox("Are you sure you want to exit", CType(MsgBoxStyle.Question + MsgBoxStyle.YesNo, MsgBoxStyle), "Confirm")
'If the user press Yes the application wil close
'because the application remains in taskmanager after closing i decide to kill the current process
If response = MsgBoxResult.Yes Then
Process.GetCurrentProcess().Kill()
ElseIf response = MsgBoxResult.No Then
e.Cancel = True
Me.WindowState = FormWindowState.Minimized
Me.Hide()
NotifyIcon1.Visible = True
End If
PS: I am not a programmer so please don't be to harsh with me:)
You don't need to Kill the current process or use the End Statement. If you have to use these then there is something amiss with your application.
When you want to end your application use Me.Close. This will fire the FormClosing event:
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Select Case MessageBox.Show("Are you sure you want to exit?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
Case Windows.Forms.DialogResult.Yes
'nothing to do here the form is already closing
Case Windows.Forms.DialogResult.No
e.Cancel = True 'cancel the form closing event
'minimize to tray/hide etc here
End Select
End Sub
To stop more than one copy of your application from running use the option to Make Single Instance Application
In the situation where you are just starting your application and are testing for previous instances I have used the VB End Statement to terminate the application.
The End statement stops code execution abruptly, and does not invoke
the Dispose or Finalize method, or any other Visual Basic code. Object
references held by other programs are invalidated. If an End statement
is encountered within a Try or Catch block, control does not pass to
the corresponding Finally block.
If Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length> 1 Then
MessageBox.Show("Another instance is running", "Error Window", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End
End If
Private Sub main_master_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If e.CloseReason = CloseReason.UserClosing Then
'Put you desired Code inside this!
Msgbox("Application Closing from Taskbar")
End If
End Sub
It will Close the exe from Taskbar or kill Process. If user Close the
Application from taskbar.
CloseReason.UserClosing
event will close the application if it is closed by User from
Taskber