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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Finchsize
  • 935
  • 2
  • 17
  • 34
  • 2
    why don't you use a view model? – Daniel A. White Jan 22 '15 at 23:43
  • Do I really need a view model to pass single object? – Finchsize Jan 22 '15 at 23:48
  • it would help with testing. – Daniel A. White Jan 22 '15 at 23:48
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Dour High Arch Jan 22 '15 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. – Finchsize Jan 23 '15 at 00:04
  • This might be a dumb question but is an instance of `MainWindow` already open when `Button_Ok_Click` is called? – Enigmativity Jan 23 '15 at 00:05
  • @Enigmativity MainWindow start to rendering after wnd.Show(); – Finchsize Jan 23 '15 at 00:08
  • Please tell us which line is `MainWindow.xaml.cs:line 143` and what `LabelFileName` is. – Dour High Arch Jan 23 '15 at 00:09
  • @DourHighArch Line 143: `LabelFileName.Content = "File Name: " + this.myFileInfo.Name.ToString();` LabelFileName is just regular XAML label, nothing special ` ` Thats pretty much all xaml for this window for now. – Finchsize Jan 23 '15 at 00:16
  • Why does `"LabelFileName "` have a space inside the quotes? Use the debugger as described in [What is a NullReferenceException](http://stackoverflow.com/questions/4660142/) and look at the value of `LabelFileName` when you assign to it. I bet it's null. – Dour High Arch Jan 23 '15 at 00:37

3 Answers3

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.

SergioL
  • 4,905
  • 3
  • 26
  • 30
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!

Oyyou
  • 610
  • 5
  • 13
  • 1
    Name is property of System.IO.FileInfo class. And it has its value before pass to second window. – Finchsize Jan 22 '15 at 23:58
  • Line 143: `LabelFileName.Content = "File Name: " + this.myFileInfo.Name.ToString();` ... – Finchsize Jan 23 '15 at 00:00
  • 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. – Finchsize Jan 23 '15 at 00:05
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.

Sean Cox
  • 782
  • 1
  • 5
  • 12
  • Secondary constructor in WPF MainWindow :) Its suicide. There is a lot more in window constructor than only this object. – Finchsize Jan 23 '15 at 00:10
  • 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. – Sean Cox Jan 23 '15 at 00:12
  • 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. – Finchsize Jan 23 '15 at 00:13
  • @TheShaman No LabelContent is not null, i check this out: `if(myFileInfo == null) MessageBox.Show("here is null");` and MessageBox popped out. – Finchsize Jan 23 '15 at 00:14