none
System.NullReferenceException: Object reference not set to an instance of an object.

    Question

  • I am getting the following stack trace when trying to use the OpenFileDialog. Does Anyone know how to fix this?

    Thanks in Advance.

    Eric Howard

    Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.

    at System.Windows.Forms.UnsafeNativeMethods.GetOpenFileName(OPENFILENAME_I ofn)
    at System.Windows.Forms.OpenFileDialog.RunFileDialog(OPENFILENAME_I ofn)
    at System.Windows.Forms.FileDialog.RunDialog(IntPtr hWndOwner)
    at System.Windows.Forms.CommonDialog.ShowDialog()
    at MyApp.FileCommands.OpenSystem(mainForm parentForm, Application dataApplication) in FileCommands.vb:line 32
    at MyApp.mainForm.cmdOpenSystem_Click(Object sender, ClickEventArgs e) in MainForm.vb:line 1013
    at C1.Win.C1Command.C1Command.OnClick(ClickEventArgs e)
    at C1.Win.C1Command.C1Command.Invoke(ClickEventArgs e)
    at C1.Win.C1Command.Y.AG(C1CommandLink 212, Z 213)
    at C1.Win.C1Command.1V.OnMouseUp(MouseEventArgs e)
    at C1.Win.C1Command.C1ToolBar.OnMouseUp(MouseEventArgs e)
    at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
    at System.Windows.Forms.Control.WndProc(Message& m)
    at System.Windows.Forms.ControlNativeWindow.OnMessage(Message& m)
    at System.Windows.Forms.ControlNativeWindow.WndProc(Message& m)
    at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
    at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
    at System.Windows.Forms.ComponentManager.System.Windows.Forms.UnsafeNativeMethods+IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
    at System.Windows.Forms.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
    at System.Windows.Forms.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
    at System.Windows.Forms.Application.Run(Form mainForm)
    at MyApp.mainForm.Main() in MainForm.vb:line 1

    Here's the code I use to call the OpenFileDialog:

    Dim _path As String
    Dim _dialog As OpenFileDialog
    Dim _result As DialogResult

    'Get Filename first
    _dialog = New OpenFileDialog

    With _dialog
       .DefaultExt = "tps"
       .Filter = "My FileType (*.mft)|*.mft|All files (*.*)|*.*"
       .FilterIndex = 1
       .Multiselect =
    False
       .Title = "Open"

       _result = _dialog.ShowDialog()   'Error Occurs at this line
    End With

    If _result = DialogResult.OK Then
       _
    path = _dialog.FileName
    End If

    _dialog.Dispose()
    _dialog = Nothing

    Monday, December 12, 2005 3:27 AM

Answers

All replies

  • The first thing I notice is that your default extension is not in your list of extensions.
    Monday, December 12, 2005 4:35 AM
  • Thanks. I noticed that and changed that. Still having the same problem.
    Monday, December 12, 2005 2:54 PM
  • What version of the framework is this?  I was unable to reproduce this, however if it's prior to 2.0, NullReferenceException can sometimes be an access violation.

    You may want to verify that you've specified an STAThread apartment for your currently executing thread. 

    http://support.microsoft.com/default.aspx?scid=kb;en-us;Q287087
    http://blogs.msdn.com/jfoscoding/archive/2005/04/07/406341.aspx

    Prior to your call to _dialog.ShowDialog() add in a MessageBox.Show(System.Threading.CurrentThread.ApartmentState.ToString()) and verify that this returns "STA".

    Tuesday, December 13, 2005 2:11 AM
  • Hello

    All the answers up to here are useless.
    I had the same problem but this is a serious framework bug because it is impossible to reproduce it. I spent two whole days with analyzing the cause but it happens from time to time. I could not find any regularity.

    The Common Dialog DLL is very buggy since many years.
    Already on Windows 98 you could easily crash your whole application by passing invalid arguments to the GetOpenFileName() API.
    Your application simply disappeared from the screen without any error message !!!!
    Windows 2000 tried to read from the floppy disk when the initial path was empty etc...
    Microsoft produces lots of Service packs but they never solve the real problems. So these bugs in Comdlg32.DLL remained 'til today.

    But this problem seams to be an additional .NET bug.
    The error message Object reference not set to an instance of an object is pure nonsense because the crash does not happen in managed code. It happens directly in Comdlg32.DLL

    The only chance you have is to rewrite the whole stuff.
    I did that in a Managed C++ DLL and now it works.

    Note:
    This code requires Win 2000 or higher and will not run on Windows 98/ME because it uses the Unicode API.
    I tested the code on Vista, where it runs perfectly.

    My code additionally resizes and centers the OpenFile dialog and switches it to report view (Detail view)

    As the OpenFolder dialog is also buggy (it never appears centerd on the screen),
    I also post the code to fix this.

    Elmue

    P.S.
    This forum's text editor has been programmed by a loser!
    If you click the Code button you lose everything you have typed!

    It puts smilies into the code!!
    It replaces u16_File[ i ] with u16_FileIdea !!
    and System:: Drawing::Rectangle with System:Big Smilerawing::Rectangle
    I had to put spaces !

    #############################################

                OpenFile and OpenFolder fixed code

    #############################################

    Header file:

    String* GetFolderDialog(int h_ParentWnd, String *s_Title, String *s_InitialPath);
    String* GetFileDialog(bool b_Open, IntPtr h_Owner, String* s_InitialFile, String* s_DefExt, String* s_Filter, String* s_Title, bool b_PathMustExist, bool b_FileMustExist, bool b_DerefLinks, bool b_MultiSelect);
    __________________________

    Cpp file:

    typedef System:: Drawing::Rectangle SysRect;

    // ######################### GetFile/Folder Callback #################################

    WCHAR   *gpu16_InitialPath;
    WNDPROC  gp_OldResizeProc;
    BOOL     gb_FirstSizing;
    BOOL     gb_SwitchReport;
    SIZE     gk_MinSize;

    LRESULT CALLBACK ResizeSubclassProc(HWND h_Dlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
        // center the window in the available screen area
        // this happens before the window becomes visible but after all initialization is done!
        if (gb_FirstSizing && uMsg == WM_WINDOWPOSCHANGED)
        {
            gb_FirstSizing = FALSE;

            if (gb_SwitchReport) // Switch File Dialog to Detail View
            {
                HWND h_ListBox  = GetDlgItem(h_Dlg, 0x460);
                HWND h_ShellWnd = GetWindow (h_ListBox, GW_HWNDNEXT);
                SendMessageW(h_ShellWnd, WM_COMMAND, 0x702C, 0);
            }

            RECT k_Wnd;
            GetWindowRect(h_Dlg, &k_Wnd);

            // retrieve the rectangle of the monitor which contains the window
            SysRect k_Bounds = Screen::GetBounds(SysRect(k_Wnd.left, k_Wnd.top, k_Wnd.right-k_Wnd.left, k_Wnd.bottom-k_Wnd.top));

            int s32_WndCX = min(k_Bounds.Width,  max(gk_MinSize.cx,  k_Wnd.right  - k_Wnd.left));
            int s32_WndCY = min(k_Bounds.Height, max(gk_MinSize.cy,  k_Wnd.bottom - k_Wnd.top));

            k_Wnd.left = max(0, k_Bounds.Left + max(0, k_Bounds.Width  - s32_WndCX) / 2);
            k_Wnd.top  = max(0, k_Bounds.Top  + max(0, k_Bounds.Height - s32_WndCY) / 2);

            SetWindowPos(h_Dlg, 0, k_Wnd.left, k_Wnd.top, s32_WndCX, s32_WndCY, SWP_NOZORDER);
            // NO return here ! MUST call OldWndProc !!!!!
        }

        return CallWindowProcW(gp_OldResizeProc, h_Dlg, uMsg, wParam, lParam);
    }

    // ######################### OpenFolderDialog #################################
     
    int CALLBACK FolderBrowserCallbackProc(HWND h_Dlg, UINT uMsg, LPARAM lParam, LPARAM lpData)
    {
        if (uMsg != BFFM_INITIALIZED)
            return 0;

        // set the initial path
        // ATTENTION: BFFM_SETEXPANDED is not supported by Windows 2000 !
        SendMessageW(h_Dlg, BFFM_SETSELECTIONW, TRUE, (LPARAM)gpu16_InitialPath);

        gb_FirstSizing   = TRUE;
        gb_SwitchReport  = FALSE;
        gk_MinSize.cx    = 415;
        gk_MinSize.cy    = 600;

        gp_OldResizeProc = (WNDPROC)SetWindowLongW(h_Dlg, GWL_WNDPROC, (LONG)ResizeSubclassProc);
        return 0;
    }

    // Workaround for bug in C# FolderBrowserDialog: the window is not centered
    // Opens the "Choose folder" window and returns the folder which the user has selected
    // returns "" if the user canceled the dialog
    String* CppUtils::Utils::GetFolderDialog(int h_ParentWnd, String *s_Title, String *s_InitialPath)
    {
        WCHAR* u16_Title  = (WCHAR*)Marshal:: StringToHGlobalUni(s_Title).      ToPointer();
        gpu16_InitialPath = (WCHAR*)Marshal:: StringToHGlobalUni(s_InitialPath).ToPointer();

        // required (see MSDN)
        LPMALLOC pMalloc = NULL;
        SHGetMalloc(&pMalloc);

        BROWSEINFOW bInfo;
        bInfo.hwndOwner      = (HWND)h_ParentWnd;
        bInfo.lpszTitle      = u16_Title;
        bInfo.ulFlags        = BIF_NEWDIALOGSTYLE | BIF_RETURNONLYFSDIRS;
        bInfo.pszDisplayName = 0; // receives only the NAME of the folder not the path !
        bInfo.pidlRoot       = 0;
        bInfo.lParam         = 0;
        bInfo.iImage         = 0;
        bInfo.lpfn           = FolderBrowserCallbackProc;

        LPITEMIDLIST pIDlist = SHBrowseForFolderW(&bInfo);

        String *s_Path = "";

        if (pIDlist != NULL)
        {
            WCHAR u16_Buf[MAX_PATH];
            u16_Buf[0] = 0;
            SHGetPathFromIDListW(pIDlist, u16_Buf);

            // Terminate path
            int Len = wcslen(u16_Buf);
            if (u16_Buf[Len -1] != '\\')
            {
                u16_Buf[Len]    = '\\';
                u16_Buf[Len +1] = 0;
            }
            s_Path = new String(u16_Buf);
        }

        // Free memory
        pMalloc->Release();
        Marshal::FreeHGlobal(u16_Title);
        Marshal::FreeHGlobal(gpu16_InitialPath);
        return s_Path;
    }

    // ################################ GetFileDialog ######################################

    #define RESULT_BUF_LEN 5000

    // OpenFile Dialog Callback sets window position and switches to Report View
    UINT CALLBACK OFNHookProc(HWND h_Hidden, UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
        if (uMsg == WM_NOTIFY)
        {
            OFNOTIFY* pNotify = (OFNOTIFY*)lParam;
            if (lParam && pNotify->hdr.code == CDN_INITDONE)
            {
                gb_FirstSizing  = TRUE;
                gb_SwitchReport = TRUE;
                gk_MinSize.cx   = 500;
                gk_MinSize.cy   = 600;

                HWND h_Dlg = GetParent(h_Hidden);
                gp_OldResizeProc = (WNDPROC)SetWindowLongW(h_Dlg, GWL_WNDPROC, (LONG)ResizeSubclassProc);
            }
        }
        return 0;
    }

    // Returns "" if user has canceled the dialog
    // Returns a full path if user selected a single file
    // Returns "Path|File1|File2|File3" if the user slected 3 files
    String* CppUtils::Utils::GetFileDialog(bool    b_Open,          // Open / Save Dialog
                                           IntPtr  h_Owner,         // Owner window
                                           String* s_InitialFile,   // file or folder
                                           String* s_DefExt,        // "wav" !! WITHOUT DOT !!
                                           String* s_Filter,        // "All Files  (*.*)|*.*"
                                           String* s_Title,         // "Please chose a file"
                                           bool    b_PathMustExist, // Error if path does not exist
                                           bool    b_FileMustExist, // Error if file does not exist
                                           bool    b_DerefLinks,    // Dereference links (return the linked file)
                                           bool    b_MultiSelect)   // Multiple Selection possible
    {
        WCHAR u16_File  [RESULT_BUF_LEN];
        WCHAR u16_Folder[MAX_PATH];

        if (!s_Filter->Length) s_Filter = L"All files  (*.*)|*.*";

        String* s_InitFile = GetFileName(s_InitialFile); // NOT Path::GetFileName !!
        String* s_InitDir  = GetPath    (s_InitialFile); // NOT Path::GetDirectoryName !!

        WCHAR* u16_Filter   = (WCHAR*)Marshal:: StringToHGlobalUni(s_Filter).  ToPointer();
        WCHAR* u16_Title    = (WCHAR*)Marshal:: StringToHGlobalUni(s_Title).   ToPointer();
        WCHAR* u16_DefExt   = (WCHAR*)Marshal:: StringToHGlobalUni(s_DefExt).  ToPointer();
        WCHAR* u16_InitFile = (WCHAR*)Marshal:: StringToHGlobalUni(s_InitFile).ToPointer();
        WCHAR* u16_InitDir  = (WCHAR*)Marshal:: StringToHGlobalUni(s_InitDir). ToPointer();

        wcscpy(u16_File,   u16_InitFile);
        wcscpy(u16_Folder, u16_InitDir);

        // replace '|' with 0 in filter string
        for (int i=0; TRUE; i++)
        {
            if (u16_Filter[ i ] == 0) { u16_Filter[i+1] = 0; break; } // assure two terminating zeroes
            if (u16_Filter[ i ] == '|') u16_Filter[ i ]   = 0;          // ORDER !!
        }

        UINT u32_Flags = OFN_ENABLESIZING | OFN_HIDEREADONLY | OFN_EXPLORER | OFN_ENABLEHOOK;

        if (b_MultiSelect)   u32_Flags |= OFN_ALLOWMULTISELECT;
        if (b_PathMustExist) u32_Flags |= OFN_PATHMUSTEXIST;
        if (b_FileMustExist) u32_Flags |= OFN_FILEMUSTEXIST;
        if (!b_DerefLinks)   u32_Flags |= OFN_NODEREFERENCELINKS;

        // CRASH in GetOpenFileName if s_InitialFile = "http://uzguzguzg"
        // If InitDir is invalid --> set Desktop directory
        if (!Directory::Exists(s_InitDir))
        {
            LPITEMIDLIST pIDlist;
            SHGetSpecialFolderLocation((HWND)(int)h_Owner, CSIDL_DESKTOPDIRECTORY, &pIDlist);
            SHGetPathFromIDListW(pIDlist, u16_Folder);
            u16_File[0] = 0;
        }

        OPENFILENAMEW k_Of;
        memset(&k_Of, 0, sizeof(OPENFILENAME));

        k_Of.lStructSize      = 88; // Windows 2000 and higher support extended dialog
        k_Of.hwndOwner        = (HWND)(int)h_Owner;
        k_Of.lpfnHook         = OFNHookProc;   
        k_Of.hInstance        = mh_Inst;

        k_Of.lpstrFilter      = u16_Filter;  // terminated with 2 zeros
        k_Of.nFilterIndex     = 1;           // 1 based !!
       
        k_Of.lpstrInitialDir  = u16_Folder;  // switch to this folder
        k_Of.lpstrFile        = u16_File;    // switch to this file and returns the result
        k_Of.nMaxFile         = RESULT_BUF_LEN;
       
        k_Of.Flags            = u32_Flags;
        k_Of.lpstrTitle       = u16_Title;   // placed in the title bar of the dialog box
        k_Of.lpstrDefExt      = u16_DefExt;  // default extension if user fails to type an extension

        BOOL b_OK;
        if (b_Open) b_OK = GetOpenFileNameW(&k_Of);
        else        b_OK = GetSaveFileNameW(&k_Of);

        if (b_OK)
        {
            // replace zeros inside the string with pipes
            // the string has two terminating zeros at the end
            if (b_MultiSelect)
            {
                for (int i=0; i<RESULT_BUF_LEN-1; i++)
                {
                    if (u16_File[ i ] == 0)
                    {
                        if (u16_File[i+1] == 0)
                            break;

                        u16_File[ i ] = '|';
                    }
                }
            }
        }
        else u16_File[0] = 0;

        Marshal::FreeHGlobal(u16_Filter);
        Marshal::FreeHGlobal(u16_Title);
        Marshal::FreeHGlobal(u16_DefExt);
        Marshal::FreeHGlobal(u16_InitDir);
        Marshal::FreeHGlobal(u16_InitFile);

        return new String(u16_File);
    }

    // ATTENTION: Path::GetFileName is USELESS !! (it may return null)
    // "E:\Temp\Test.jpg" --> "Test.jpg"
    String* CppUtils::Utils::GetFileName(String* s_Path)
    {
        int s32_Pos = s_Path->LastIndexOf("\\");
        if  (s32_Pos < 0) return s_Path;

        return s_Path->Substring(s32_Pos +1);
    }

    // ATTENTION: Path::GetDirectoryName is USELESS !! (it may return null)
    // "E:\Temp\Test.jpg" --> "E:\Temp\"
    String* CppUtils::Utils::GetPath(String* s_Path)
    {
        int s32_Pos = s_Path->LastIndexOf("\\");
        if  (s32_Pos < 0) return "";

        return s_Path->Substring(0, s32_Pos +1);
    }

    Wednesday, May 16, 2007 8:22 AM
  • Just an FYI it's actually "System.Threading.Thread.CurrentThread.ApartmentState.ToString()"
    Thursday, June 07, 2007 10:07 PM
  • I got a similar problem and i guess that the Modal Form are not handling the objects in the form when the dialog result is set, so i clear all the object in the modal form before to set the DialogResult and it works for me.


     

    Monday, May 31, 2010 5:31 PM