41244

Trouble with raising custom event handling between 2 forms

Question:

New to C#. Like the title, I'm having difficulty trying to raise an event. It will eventually then be consumed on another form.

What I'm trying to do is have many instances of a custom user control (my event raising form(s)) that creates a tcp client, connects, and then closes. When this tcp client has an "error", be it a catch exception, I want an event to be raised. I'm forcing the error right now by having my internet turned off to test. My first problem is I can't even get the event to be raised at all. I'll show the event code I'm working with on my custom user control:

public delegate void TaskCompleteEventHandler(object sender, TaskCompleteEventArgs e); public event TaskCompleteEventHandler TaskComplete; public class TaskCompleteEventArgs : System.EventArgs { // add local member variables to hold text private string errorString; // class constructor public TaskCompleteEventArgs(string ErrorString) { this.errorString = ErrorString; } // Property public string ErrorString { get { return errorString; } set { errorString = value; } } }

This is my method that processes the exception and ideally would raise the event and allow the host form to print the string and exception accordingly.

private void ErrorLogging(string ex) { errorString = String.Format(/*...errorString formatting...*/); // instance the event args and pass it the errorString value TaskCompleteEventArgs args = new TaskCompleteEventArgs(errorString); // raise the event with the updated arguments TaskComplete(this, args); //----> THIS IS WHERE I GET AN ERROR!! <---- this.Dispose(); }

The error is <strong>Object reference not set to an instance of an object.</strong> Here's the Watch screen of my TaskComplete(this, args)

<img alt="watchscreen" class="b-lazy" data-src="https://i.stack.imgur.com/Ferel.jpg" data-original="https://i.stack.imgur.com/Ferel.jpg" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />

I can't seem to debug this... I'm just not strong enough yet to know what I've done wrong. How is it causing side effects?

I'm sure I'm going to have more issues on my main form when I get this going... Does anyone have a clue what's causing this? Thanks in advance.

<hr />

EDIT: On my main form:

public Form1() { InitializeComponent(); // Start control disabled and subscribe each control the event foreach (var control in controlList) { control.Enabled = false; control.TaskComplete += new dev_emu_project.dev_emu_widget.TaskCompleteEventHandler(OnTaskComplete); } } List<dev_emu_project.dev_emu_widget> controlList = new List<dev_emu_project.dev_emu_widget>(); public void OnTaskComplete(object sender, dev_emu_project.TaskCompleteEventArgs e) { //.... work for processing } }

Answer1:

You are getting a NullReferenceException because you're invoking an empty event, meaning no delegate has been registered to it. You need to make sure TaskComplete isn't null before invoking it.

Add a null check before invoking to make sure someone did register to your event:

if (TaskComplete != null) { TaskComplete(this, args); }

From MSDN <a href="http://msdn.microsoft.com/en-us/library/aa645739%28v=vs.71%29.aspx" rel="nofollow">Event Tutorial</a>:

<blockquote>

<strong>Invoking an event</strong>

Once a class has declared an event, it can treat that event just like a field of the indicated delegate type. The field will either be null, if no client has hooked up a delegate to the event, or else it refers to a delegate that should be called when the event is invoked. Thus, invoking an event is generally done by first checking for null and then calling the event

</blockquote>

Recommend

  • HALF_PTR Windows data type
  • UIBarButtonItem's action is not called when in a view with a UIGestureRecognizer
  • Exception HRESULT: 0x800455BC in speech recognition in Windows phone 8
  • How to access recipient on sent messages page with mailboxer
  • Can XOR be expressed using SKI combinators?
  • F#: In which memory area is the continuation stored: stack or heap?
  • Most efficient way to move table rows from one table to another
  • Click on button in another program - FindWindow, C#
  • ThreadStatic in asynchronous ASP.NET Web API
  • SetWindowsHookEx does not react on media keys
  • Can't delete or rename original file after resizing
  • c# open webrowser in many tab
  • ADO and msqli connections very slow
  • How to Cache Real-time Data?
  • PHP buffered output depending on server setting?
  • output of program is not same as passed argument
  • How to extract text from Word files using C#?
  • MySQL WHERE-condition in procedure ignored
  • Javascript + PHP Encryption with pidCrypt
  • Web-crawler for facebook in python
  • Akka Routing: Reply's send to router ends up as dead letters
  • AT Commands to Send SMS not working in Windows 8.1
  • Unit Testing MVC Web Application in Visual Studio and Problem with QTAgent
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • trying to dynamically update Highchart column chart but series undefined
  • Angular 2 constructor injection vs direct access
  • Trying to get generic when generic is not available
  • How do I configure my settings file to work with unit tests?
  • Getting Messege Twice Using IMvxMessenger
  • Java static initializers and reflection
  • Android Google Maps API OnLocationChanged only called once
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • Is it possible to post an object from jquery to bottle.py?
  • Does armcc optimizes non-volatile variables with -O0?
  • costura.fody for a dll that references another dll
  • How can i traverse a binary tree from right to left in java?
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?
  • java string with new operator and a literal
  • How can I use threading to 'tick' a timer to be accessed by other threads?