Object reference not set to an instance of an object.

simsenVejle

Well-known member
Joined
Feb 14, 2021
Messages
46
Programming Experience
Beginner
I have used all day to figure out what happens, and why this errormessage is shown when I link to a view with data from db. But is fine, when only viewing some textstring.

My solution have 5 projects: TheUI, DAL, Model, ViewModel and Views. When run to curser method I can see that the 3 rows from the db goes fine into the Views (UserControls), but when linking on the UI to the specifc UserControl something goes wrong.

I'm pretty sure, there is nothing wrong with DAL and Model, so I'm showing you the 3 other projects.

If you want the hole code, just say so. Nothing secret here. But I don't have a place to upload, so I need a email account to send you the solution as zip file.

If you want to see the 2 other projects, just say so.

Best regards

Simsen :)


ViewModel.Account.CategoryViewModel:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using Model.Account;
using DAL.Account;


namespace ViewModel.Account
{
    public class CategoryViewModel
    {
        private Category _selectedCategory;
        public MyICommand DeleteCommand { get; set; }
        public Category SelectedCategory
        {
            get
            {
                return _selectedCategory;
            }

            set
            {
                _selectedCategory = value;
                DeleteCommand.RaiseCanExecuteChanged();
            }
        }

        public CategoryViewModel()
        {
            LoadCategories();
            DeleteCommand = new MyICommand(OnDelete, CanDelete);
        }

        public ObservableCollection<Category> Categories { get; set; }

        public void LoadCategories()
        {
            DalCategory dalCategory = new DalCategory();
            ObservableCollection<Category> dalCategories = dalCategory.GetCategories();
            Categories = dalCategories;
        }

        #region Delete
        private void OnDelete()
        {
            Categories.Remove(SelectedCategory);
        }

        private bool CanDelete()
        {
            return SelectedCategory != null;
        }
        #endregion
    }
}

Views.CategoryView.CategoryView.xaml:
<UserControl x:Class="Views.Account.CategoryView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:viewModel = "clr-namespace:ViewModel.Account;assembly=ViewModel"
             xmlns:data = "clr-namespace:Model.Account;assembly=Model"
            
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <StackPanel Orientation = "Horizontal">
            <ListBox ItemsSource = "{Binding Mode=OneWay}">
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding CategoryId}" />
                        <TextBlock Text="{Binding CategoryName}" />
                        <TextBlock Text="{Binding CategoryIsGlobal}" />
                        <TextBlock Text="{Binding ProjectId}" />
                        <TextBlock Text="{Binding IsObsolete}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox>
        </StackPanel>
    </Grid>
</UserControl>
Views.CategoryView.CategoryView.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Views.Account
{
    /// <summary>
    /// Interaction logic for CategoryView.xaml
    /// </summary>
    public partial class CategoryView : UserControl
    {
        public CategoryView()
        {
            InitializeComponent();
            this.DataContext = new ViewModel.Account.CategoryViewModel();
            string HereICheckTheDataContextAndItHas3Rows = "";
        }
    }
}

AnsiBug.MainWindow.xaml:
<Window xmlns:syncfusion="http://schemas.syncfusion.com/wpf" x:Name="AnsiBug"  x:Class="AnsiBug.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:AnsiBug"
        xmlns:views = "clr-namespace:Views.Account;assembly=Views"
        mc:Ignorable="d"
        Title="MainWindow" Height="800" Width="1200" HorizontalAlignment="Center" VerticalAlignment="Center" WindowStartupLocation="CenterScreen">
    <Window.Resources>
        <!--#region Context Menus-->
        <!--#region Reports-->
        <ContextMenu x:Key="cmBtnReports" >
            <MenuItem x:Name="BtnTextReports" Header="Tekst rapporter" />
            <MenuItem x:Name="BtnReporsMyBugs" Header="Mine fejl" />
            <MenuItem x:Name="BtnReporsNewBugs" Header="Nye fejl" />
            <MenuItem x:Name="BtnReporsAllBugs" Header="Alle fejl" />
            <MenuItem x:Name="BtnReporsClosedBugs" Header="Lukkede fejl" />
            <MenuItem x:Name="BtnReporsNoAssignedBugs" Header="Ikke tildelte fejl" />
        </ContextMenu>
        <!--#endregion-->
        <!--#region Administration-->
        <ContextMenu x:Key="cmBtnAdministration" >
            <MenuItem x:Name="BtnShowUsers" Header="Vis brugere" />
            <MenuItem x:Name="BtnAddUser" Header="Tilføj bruger" />
            <MenuItem x:Name="BtnEditAccount" Header="Ret konto" />
            <MenuItem x:Name="BtnShowProjects" Header="Vis projekter" />
            <MenuItem x:Name="BtnAddProject" Header="Tilføj projekt" />
            <MenuItem x:Name="BtnManagement" Header="Vedligeholdelse" />
        </ContextMenu>
        <!--#endregion-->
        <!--#region Preferences-->
        <ContextMenu x:Key="cmBtnPreferences" >
            <MenuItem x:Name="BtnMyInfo" Header="Min info" />
        </ContextMenu>
        <!--#endregion-->
        <!--#region Preferences-->
        <ContextMenu x:Key="cmBtnLists" >
            <MenuItem x:Name="BtnMyBugs" Header="Mine fejl" />
            <MenuItem x:Name="BtnNewBugs" Header="Nye fejl" />
            <MenuItem x:Name="BtnAllBugs" Header="Alle fejl" />
            <MenuItem x:Name="BtnUnAssignedBugs" Header="Ikke tildelte fejl" />
            <MenuItem x:Name="BtnClosedBugs" Header="Lukkede fejl" />
        </ContextMenu>
        <!--#endregion-->
        <!--#region Projects-->
        <ContextMenu x:Key="cmBtnProjects" >
            <MenuItem x:Name="BtnDashBoard" Header="Dashboard" />
            <MenuItem x:Name="BtnNewBug" Header="Ny fejl" />
        </ContextMenu>
        <!--#endregion-->
        <!--#endregion-->
    </Window.Resources>
    <Window.FocusVisualStyle>
        <Style/>
    </Window.FocusVisualStyle>
    <StackPanel>
        <Grid Margin="5">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="250"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="150"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="130" />
                <RowDefinition Height="600" />
            </Grid.RowDefinitions>
            <Image Source="/Images/Logo/ANSI.gif" Grid.Row="0" Grid.Column="0" Height="100" />
            <Image Source="/Images/Logo/logoBug.gif" Grid.Row="0" Grid.Column="2" Height="100" />
            <Grid Grid.Column="1">
                <Grid Margin="5">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="180" />
                    </Grid.RowDefinitions>
                    <StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="0" Margin="5 0 0 0">
                        <Button x:Name="BtnProjects" Content="Projekter" Style="{StaticResource TopMenuButton}" Click="BtnTopMenu_Click" />
                        <Image Source="/Images/TopDivider.jpg" />
                    </StackPanel>
                    <StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="1" Margin="5 0 0 0">
                        <Button x:Name="BtnLists" Content="Lister" Style="{StaticResource TopMenuButton}" Click="BtnTopMenu_Click" />
                        <Image Source="/Images/TopDivider.jpg" />
                    </StackPanel>
                    <StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="2" Margin="5 0 0 0">
                        <Button x:Name="BtnPreferences" Content="Indstillinger" Style="{StaticResource TopMenuButton}" Click="BtnTopMenu_Click" />
                        <Image Source="/Images/TopDivider.jpg" />
                    </StackPanel>
                    <StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="3" Margin="5 0 0 0">
                        <Button x:Name="BtnAdministration" Content="Administration" Style="{StaticResource TopMenuButton}" Click="BtnTopMenu_Click" />
                        <Image Source="/Images/TopDivider.jpg" />
                    </StackPanel>
                    <StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="4" Margin="5 0 0 0">
                        <Button x:Name="BtnReports" Click="BtnTopMenu_Click" Content="Rapporter" Style="{StaticResource TopMenuButton}" />
                        <Image Source="/Images/TopDivider.jpg" />
                    </StackPanel>
                    <StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="5" Margin="5 0 0 0">
                        <Button x:Name="BtnLogout" Click="BtnLogout_Click" HorizontalAlignment="Right" HorizontalContentAlignment="Right" Content="Log ud" Style="{StaticResource TopMenuButton}" />
                        <Image Source="/Images/TopDivider.jpg" />
                    </StackPanel>
                </Grid>
            </Grid>
            <Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Margin="25">
                <views:CategoryView x:Name="CategoryView" Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="2" />               
            </Grid>
        </Grid>
    </StackPanel>
</Window>

AnsiBug.MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace AnsiBug
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            HideUserControls();
            //CategoryView.Visibility = Visibility.Visible;
        }

        private void HideUserControls()
        {
            //StudentView.Visibility = Visibility.Hidden;
            //CategoryView.Visibility = Visibility.Hidden;
        }

        #region Topmenu knapper

        private void BtnLogout_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void BtnTopMenu_Click(object sender, RoutedEventArgs e)
        {
            var button = (Button)sender;
            string btnName = "cm" + button.Name;
            ContextMenu cm = this.FindResource(btnName) as ContextMenu;
            cm.PlacementTarget = sender as Button;
            cm.IsOpen = true;
        }

        #endregion
    }
}
 
Moving to WPF...

It would help us dramatically if you tell us which line of code the exception is being thrown on. If Visual Studio is not stopping on a particular line of code, turn on First Chance exceptions so that you see when the exception is first thrown, but before it gets handled.
 
Moving to WPF...

It would help us dramatically if you tell us which line of code the exception is being thrown on. If Visual Studio is not stopping on a particular line of code, turn on First Chance exceptions so that you see when the exception is first thrown, but before it gets handled.
O I'm so sorry it is this line and it is in MainWindow.xaml

<views:CategoryView x:Name="CategoryView" Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="2" />
 
O I'm so sorry it is this line and it is in MainWindow.xaml

<views:CategoryView x:Name="CategoryView" Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="2" />
And sorry not to post in correct group - I have difficulties to see what should be in witch group. I hope you can forgive me.
 
And when it stops on that line, the exception window that pops up should have an "Exception details". That should show you callstack and potentially an inner exception. Does the callstack or the callstack of the inner exception point to where the null object is being used/referenced?
 
And when it stops on that line, the exception window that pops up should have an "Exception details". That should show you callstack and potentially an inner exception. Does the callstack or the callstack of the inner exception point to where the null object is being used/referenced?
When removing all try catch in the hole solution the stack trace says it is in the DAL.Helper.Conn() method

I have attached the solution if that is more easy instead of me babbling

My Helper Class looks like this (without try catch);


Helper class:
using System;
using System.Configuration;

namespace DAL
{
    public class Helper
    {
        private static readonly string ConnectionStringName = "AnsiBugDb";

        //In this the stack trace says the error is
        public static string Conn()
        {
            return ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString;
        }
    }
}
 

Attachments

  • AnsiBugSolutionBackup20210319.zip
    506.1 KB · Views: 81

Latest posts

Back
Top Bottom