Hi,

I have voidmain() function in Program.cs

[STAThread]
        static void Main(string[] args)
        {  


            Application.EnableVisualStyles();

        Application.SetCompatibleTextRenderingDefault(false);

        frmMain main = new frmMain();

        MainTool.frmmain = main;                   


        if (args != null && args.Length > 0)
        {

            Application.Run(new frmMain(args[0].ToString()));

        }

        else
        {
            Application.Run(main);
        }                 
    }      


 In that: MainTool.frmmain = main;     

Assign frmmain variable of MainTool class (data processing class) with frmMain of Form Main.

The reason to do so is because I have a class data processing Excel file: MainTool.cs in the project declare frmmain variables for calling formMain.

The problem will not happen if I do not make the registration program on Windows Context Menu. To do that, I must take the path of the file into the program. Like this:

            if (args != null && args.Length > 0)
            {

                Application.Run(new frmMain(args[0].ToString()));

            }
            else
            {
                Application.Run(main);
            }

If so, I still miss main variables above. When you debug programs appear error: object reference not set to an instance of an object. Because not set args[0] for the main variables.

How to assign?

Thanks!

The args parameter to the Main function is a list of command line parameters. If I run the following command from a cmd prompt:

MyApplication.exe -e 5

Then args[0] will be set to "-e" and args[1] will be set to "5". Note that the arguments are strings already (since args is a string[]) so there is no need to convert them using ToString() method.

Hi darkagn,

So, how to solve with error: "object reference not set to an instance of an object" that I encountered?

You need to work out exactly which object is yet to be initialised by stepping through your code with the debugger. The code you have posted looks correct, I am guessing the error is actually occurring in the constructor for frmMain, or maybe that MainTool.frmmain is not set to the same instance of frmMain.

Application.Run(new frmMain(args[0].ToString()));

The above line of code creates a new instance of frmMain, so MainTool.frmmain is no longer pointing to the right place. A better way of doing it would be to create a string property in your frmMain class called Path and doing the following:

frmMain main = new frmMain();
MainTool.frmmain = main;
if (args != null && args.Length > 0)
    main.Path = args[0];
Application.Run(main);
This article has been dead for over six months. Start a new discussion instead.