?
Solved

NullReferenceException was unhandled - error when using startup form in C Sharp?

Posted on 2011-04-28
8
Medium Priority
?
687 Views
Last Modified: 2012-05-11
Please note image below of where error is occuring and the entire code is presented below....
I have a timer on this form that fires after a minute's time and runs the code found in tRecords_Tick...if I have to do a

frmMain form as New frmMain - where do I put it at when I already have Form_Load coding?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;

namespace Logger
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();

        }

        private void frmMain_Load(object sender, EventArgs e)
        {

            VisualData();
        }

        public void VisualData()

        {
            ArrayList sequence = new ArrayList();

            string sSQL = "";

            // had to adjust CHARINDEX('\\' 

            sSQL = "SELECT REPLACE(REVERSE(LEFT(REVERSE(DBName),CHARINDEX('\\', REVERSE(DBName),1)-1)), '.accdb', '') AS [Database Name], Access_USERS.[Full Name] as [User], Access_USERS.EXt as Ext, Access_USERS.CPU, substring(convert(varchar(20), Access_LOGGER.InDate, 9), 13, 5) as [Time In]";
            sSQL = sSQL + " FROM (Access_LOGGER INNER JOIN Access_DBLIST ON Access_LOGGER.fDBID = Access_DBLIST.ID) INNER JOIN Access_USERS ON Access_LOGGER.fUserID = Access_USERS.ID";
            sSQL = sSQL + " WHERE Access_USERS.WinSign<>'slecompte' AND Access_LOGGER.OutDate Is Null";
            sSQL = sSQL + " ORDER BY [Time In]";

            // do not put \\EC-SQL front of

            string conn = "Data Source=EC-SQL;Initial Catalog=NEWEQ;User Id=NEWEQ;Password=n3w3@!;";

            SqlConnection sqlCon = null;
            try
            {
                sqlCon = new SqlConnection();
                sqlCon.ConnectionString = conn;
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = sqlCon;
                cmd.CommandText = sSQL;
                sqlCon.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    LogInfo m = new LogInfo();
                    m.DBName = reader[0].ToString();
                    m.User = reader[1].ToString();
                    m.Ext = reader[2].ToString();
                    m.CPU = reader[3].ToString();
                    m.TimeIn = reader[4].ToString();

                    //MessageBox.Show(reader[0].ToString());

                    sequence.Add(m);
                }

                dgvLogger.DataSource = sequence;

            }
            finally
            {
                sqlCon.Close();
            }


        }

        private void frmMain_MouseClick(object sender, MouseEventArgs e)
        {
            frmMain.ActiveForm.Opacity = 100;
        }

        private void frmMain_Leave(object sender, EventArgs e)
        {
            frmMain.ActiveForm.Opacity = 90;
        }

        private void tRecords_Tick(object sender, EventArgs e)
        {
            if (People_Logged_In() == true)
            {
                frmMain.ActiveForm.Visible = true;
            }
            else
            {
                 frmMain.ActiveForm.Visible = false;
            }

        }

        //
        
        private static Boolean People_Logged_In()
        {

            frmMain.ActiveForm.Text = "EC Access databases users:   **** checking status ****";

            System.Windows.Forms.Application.DoEvents();

            Boolean bHasRows;
            string sSQL = "";

            // had to adjust CHARINDEX('\\' 

            sSQL = "SELECT REPLACE(REVERSE(LEFT(REVERSE(DBName),CHARINDEX('\\', REVERSE(DBName),1)-1)), '.accdb', '') AS [Database Name], Access_USERS.[Full Name] as [User], Access_USERS.EXt as Ext, Access_USERS.CPU, substring(convert(varchar(20), Access_LOGGER.InDate, 9), 13, 5) as [Time In]";
            sSQL = sSQL + " FROM (Access_LOGGER INNER JOIN Access_DBLIST ON Access_LOGGER.fDBID = Access_DBLIST.ID) INNER JOIN Access_USERS ON Access_LOGGER.fUserID = Access_USERS.ID";
            sSQL = sSQL + " WHERE Access_USERS.WinSign<>'slecompte' AND Access_LOGGER.OutDate Is Null";
            sSQL = sSQL + " ORDER BY [Time In]";

            // do not put \\EC-SQL front of

            string conn = "Data Source=EC-SQL;Initial Catalog=NEWEQ;User Id=NEWEQ;Password=n3w3@!;";

            SqlConnection sqlCon = null;
            try
            {
                sqlCon = new SqlConnection();
                sqlCon.ConnectionString = conn;
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = sqlCon;
                cmd.CommandText = sSQL;
                sqlCon.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                bHasRows = reader.HasRows;

                frmMain.ActiveForm.Text = "EC Access databases users:";
                System.Windows.Forms.Application.DoEvents();

                if (bHasRows == true)
                {
                    return true;
                } 
                else 
                {
                    return false;
                }
            }

            finally
            {
                sqlCon.Close();
            }

            //frmMain.ActiveForm.Text = "EC Access databases users:";
            //System.Windows.Forms.Application.DoEvents();

        }

    }
}

Open in new window

error.png
0
Comment
Question by:stephenlecomptejr
8 Comments
 
LVL 17

Accepted Solution

by:
Carlos Villegas earned 2000 total points
ID: 35487603
I think that is fine, but you must consider that your application can lost the focus, so Form.ActiveForm will be null, to handle that just:

       private static Boolean People_Logged_In()
        {
             if (Form.ActiveForm == null)
                 return;
            frmMain.ActiveForm.Text = "EC Access databases users:   **** checking status ****";

            System.Windows.Forms.Application.DoEvents();

Open in new window


The same wherever your use Form.ActiveForm
0
 
LVL 7

Expert Comment

by:OklahomaDave
ID: 35487784
Actually, that code snippet should read "if (frmMain.ActiveForm == null)"...

-David
0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 35487821
@OklahomaDave, that's not right, ActiveForm is a Form class static member, so the clear way is Form.ActiveForm
0
Veeam and MySQL: How to Perform Backup & Recovery

MySQL and the MariaDB variant are among the most used databases in Linux environments, and many critical applications support their data on them. Watch this recorded webinar to find out how Veeam Backup & Replication allows you to get consistent backups of MySQL databases.

 
LVL 7

Expert Comment

by:OklahomaDave
ID: 35487870
And since frmMain is derived from Form, it should have the same static members as the base Form class.  Either way, in reality, works.

-David
0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 35488078
Well. my point is that Form.ActiveForm can be any form instance, so referencing it by using a var name (in this case frmMain) is less clear for me.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35488302
Well. my point is that Form.ActiveForm can be any form instance, so referencing it by using a var name (in this case frmMain) is less clear for me.
The author named his class "frmMain"

public partial class frmMain : Form

Open in new window


so he's still making a class-level access, it's just further down the inheritance chain  = )
0
 
LVL 1

Author Comment

by:stephenlecomptejr
ID: 35488360
Thank you very much to all!
0
 
LVL 17

Expert Comment

by:Carlos Villegas
ID: 35488559
Well well, Ok that's fine, there is no problem, just that David said:
Actually, that code snippet should read "if (frmMain.ActiveForm == null)"...
Why? I wrote it... then I said:
@OklahomaDave, that's not right, ActiveForm is a Form class static member, so the clear way is Form.ActiveForm
Ok Did not have to say "that's not right", nothing is wrong, just my point of view and what makes sense to me, is the same thing.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Simulator games are perfect for generating sample realistic data streams, especially for learning data analysis. It is even useful for demoing offerings such as Azure stream analytics, PowerBI etc.
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses
Course of the Month15 days, 5 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question