1

trying to finish up my little windows form app I wrote in C#. I build it without errors exept for the variable "e" which is never used.
When I run the program after building it nothing happends and in event viewer I get a .net runtime error (Pasted below). Code:

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        private Thread thread;

        public Form1()
        {
            InitializeComponent();
            richTextBox1.Text = "Epic pinger";

            Form1.ActiveForm.FormClosing += new FormClosingEventHandler(Form1_Closing);
        }
        private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (thread != null)
            {
                thread.Abort();
            }
        }


        public void ping()
        {
            string textb1 = textBox1.Text;
            try
            {
                while (true)
                {

                    if (textb1 == "")
                    {
                        return;
                    }

                    using (Ping p = new Ping())
                    {
                        //Konfigurerings boksene int/strings
                        string msStørreKonf2 = msKonfig2.Text;
                        string msStørre = textBox2.Text;
                        int msStørst = 100;
                        int msKonf2t = 100;
                        Int32.TryParse(msStørreKonf2, out msKonf2t);
                        Int32.TryParse(msStørre, out msStørst);


                        this.Invoke((MethodInvoker)delegate

                        {
                            try
                            {
                                listView1.Items.Add(p.Send(textBox1.Text).RoundtripTime.ToString() + "ms\n");
                                if (p.Send(textBox1.Text).RoundtripTime > msStørst) { Console.Beep(1500, 400); } //konfig boks 1
                                if (p.Send(textBox1.Text).RoundtripTime > msKonf2t) { Console.Beep(6500, 700); } //konfig boks 2
                                listView1.EnsureVisible(listView1.Items.Count - 1);
                            }
                            catch (PingException e)
                            {
                                Console.Beep(5000, 100);
                                richTextBox1.AppendText("Error med ping addressen eller pip konfigurasjon! ");
                            }
                        });
                     //Søvetid, henter input fra tidsBox. 
                        string tidPingString = tidsBox.Text;
                        int tidPing = 1000;
                        Int32.TryParse(tidsBox.Text, out tidPing);
                        Thread.Sleep(tidPing);
                        // testing:



                    }
                }
            }
            catch (ThreadAbortException e)
            {
                // Ska vær blank!
            }

        }


        private void button1_Click(object sender, EventArgs e)
        {
            if (thread != null && thread.IsAlive)
            {
                thread.Abort();
                listView1.Items.Add("|");
            }
            else
            {
                thread = new Thread(new ThreadStart(ping));
                thread.Start();
            }
        }

Error XML view:

- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name=".NET Runtime" /> 
  <EventID Qualifiers="0">1026</EventID> 
  <Level>2</Level> 
  <Task>0</Task> 
  <Keywords>0x80000000000000</Keywords> 
  <TimeCreated SystemTime="2016-06-30T07:40:42.499533800Z" /> 
  <EventRecordID>40977</EventRecordID> 
  <Channel>Application</Channel> 
  <Computer>computername.domainname</Computer> 
  <Security /> 
  </System>
- <EventData>
  <Data>Application: EndlessP.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.NullReferenceException at WindowsFormsApplication2.Form1..ctor() at WindowsFormsApplication2.Program.Main()</Data> 
  </EventData>
  </Event>

It's solved, look at comments to see the solution. If I can i'll try to add the explanation here of why it happened.

Zeay
  • 19
  • 4
  • Realised some formatting errors in the question. Sorry about that, my second post here – Zeay Jun 30 '16 at 07:47
  • do you know where exactly the exception is thrown? – Nitro.de Jun 30 '16 at 07:49
  • I don't, sorry. Currently reading trough Rene's answer. @Nitro.de – Zeay Jun 30 '16 at 07:52
  • 3
    In this line `Form1.ActiveForm.FormClosing += new FormClosingEventHandler(Form1_Closing);` there is no ActiveFrom yet in the constructor. use `this.FormClosing += new FormClosingEventHandler(Form1_Closing);` instead. – rene Jun 30 '16 at 07:52
  • Just debug your code and find the line that throws null reference exception. Then you can solve it. And variable e never used must be a Warning, not Error. – uTeisT Jun 30 '16 at 07:54
  • Just attach the debugger, set a breakpoint on `InitializeComponent` (Hit F9 to set the break point), then Start debugging (F5). Inspect Form1.ActiveFrom – rene Jun 30 '16 at 07:54
  • Change the `Form1.ActiveForm.FormClosing`with `This.FormClosing` – Aimnox Jun 30 '16 at 07:56
  • To get rid of the warning `catch (PingException e)` remove the `e` or use it for logging. – rene Jun 30 '16 at 07:56
  • That worked :D If anyone don't mind explaining why it came with a error? Gonna try to not make the same mistake again :P – Zeay Jun 30 '16 at 07:58
  • @Zeay Rene already explained. You try to access the `ActiveForm` property of Form1 which is `null` in your code. – Nitro.de Jun 30 '16 at 08:03

2 Answers2

4

Form1.ActiveForm will be null in your case. You need to set the event for the current form instance, which is simply this:

this.FormClosing += new FormClosingEventHandler(Form1_Closing);

It's even better not to attach the event manually but to use the form's properties window.


Explanation: The Form.ActiveForm property is set to the form's instance that is currently active. This property may be null in various cases, for example also when there are instances of the form that are not active. This is the problem in your case. When the constructor executes, there's an instance of the form, but it is not visible yet and thus not active.

So using ActiveForm to attach events may even be dangerous! Imagine the case when there are already instances of your form and one of them is visible. Now you create another instance. The event will be attached to the currently active instance (which may be a totally different instance), instead of the current instance.

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
2

If you are getting error for the NullReference Exception then It indicates that you are trying to access fields,function types that points to null. So it is better to check the value where you are assigning is null or not. eg

 string myname=null;
   if (myname.Length == 0) // will generate exception
    {
    Console.WriteLine(myname); //it will never get here.
    }
Robert
  • 5,278
  • 43
  • 65
  • 115