0

I tried to pass object to the next window, but I'm getting a Null exception. So in my first window:

        private void Button_Ok_Click(object sender, RoutedEventArgs e)
        {
           if (file == null)
           {
              System.Windows.MessageBox.Show("null");
              return;
           }
           MainWindow wnd = new MainWindow
           {
              myFileInfo = file
           };
           if(wnd.myFileInfo == null)
              System.Windows.MessageBox.Show("null2");
           wnd.Show();
        }

MessegeBox do not appear so file and wnd.myFileInfo are definetly not null.

Second window:

    public partial class MainWindow : Window
    {
      public FileInfo myFileInfo;
      //...
      public MainWindow()
      {
          InitializeComponent();
          LabelFileName.Content = "File Name: " + this.myFileInfo.Name.ToString(); // Null exception
      //...
      }
    }

I did everything I can to find a solution, unfortunately unsuccessful.

XAML:

<Grid>
    <Label Name="LabelFileName" Grid.Column="0" Grid.Row="0" />
</Grid>

Exception Message: {"Object reference not set to an instance of an object."}

Stack Trace :

   at Charts.MainWindow..ctor() in c:\Users\Daniel\Documents\Visual Studio 2012\Projects\Charts\Charts\MainWindow.xaml.cs:line 143
   at Charts.Init.Button_Ok_Click(Object sender, RoutedEventArgs e) in c:\Users\Daniel\Documents\Visual Studio 2012\Projects\Charts\Charts\Init.xaml.cs:line 84
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
   at System.Windows.Controls.Primitives.ButtonBase.OnClick()
   at System.Windows.Controls.Button.OnClick()
   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
   at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
   at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
   at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at System.Windows.Application.Run()
   at Charts.App.Main() in c:\Users\Daniel\Documents\Visual Studio 2012\Projects\Charts\Charts\obj\Debug\App.g.cs:line 0
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Ok, i understood why it gives me null exception. I try to create new window with parameter. First MainWindow class is trying to call constructor, after constructor it would set parameter to object. As long as im using this object before constructor is done its obvious thats its going to give me null exception.

10
  • 2
    why don't you use a view model? Commented Jan 22, 2015 at 23:43
  • Do I really need a view model to pass single object? Commented Jan 22, 2015 at 23:48
  • it would help with testing. Commented Jan 22, 2015 at 23:48
  • possible duplicate of What is a NullReferenceException and how do I fix it? Commented Jan 22, 2015 at 23:52
  • @DourHighArch I understund what is NullException, but I have no idea why object which is initialized and definetly not null before pass, it becomes not initialized - null in next window. Commented Jan 23, 2015 at 0:04

3 Answers 3

1

Have you considered looking into a messaging framework? Such as the ones included in MVVMLight, Jounce, or any number of other MVVM frameworks? However, it's not difficult to roll your own event aggregator. You would have to have a mechanism for both windows to obtain an instance of the event aggregator; either through some sort of service locator or dependency injection framework, or even creating it as a property off your main app class.

With messaging, you'd essentially send a message from your first window and your second window would listen for it.

In your scenario, your button click would show the window then publish the message. The second window upon receiving the message would be able to act upon its content.

Sign up to request clarification or add additional context in comments.

Comments

0

If you're doing "ToString()" on the name, does that mean the type of "Name" isn't string already? And if that is the case, then I guess you should give it a value, or at least instantiate it?

Line 143, what is it?

Eeesh. Put a break point on that line, hover over every object and property and find out what is null. This is bugging me, and I want to know!

3 Comments

Name is property of System.IO.FileInfo class. And it has its value before pass to second window.
Line 143: LabelFileName.Content = "File Name: " + this.myFileInfo.Name.ToString(); ...
I dont need a break point there as long as im getting null exception there program will stop there anyway. I know what is null, as I mentioned its myFileInfo object of FileInfo class that i try to pass.
0

Could you not add a secondary constructor for the second window? Then pass the object to the constructor.

 public partial class MainWindow : Window
    {
      public FileInfo myFileInfo;
      //...
public MainWindow(FileInfo theInfo)
{
InitializeComponent();
myFileInfo = theInfo;
}

      public MainWindow()
      {
          InitializeComponent();
          LabelFileName.Content = "File Name: " + this.myFileInfo.Name.ToString(); // Null exception
      //...
      }
    }

Then when you create the new window, pass in the file info object.

4 Comments

Secondary constructor in WPF MainWindow :) Its suicide. There is a lot more in window constructor than only this object.
Yeah, I actually didn't see where you set the public property in the class, that's why I suggested the secondary constructor. My guess is that LabelContent is null.
I can do that in several ways, singleton class, ViewModel (as someone mentioned before) either way im curious why this one gives me null exception.
@TheShaman No LabelContent is not null, i check this out: if(myFileInfo == null) MessageBox.Show("here is null"); and MessageBox popped out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.