-1

I've been learning C# and I've been watching a Udemy course. My knowledge of SQL is quite limited. I was watching a lecture and I'm now following steps to make a simple WPF app that will display data from two tables and let me add, remove or update data in the two tables.

The code is as follows:

XAML markup:

<Window x:Class="SQL_Application_WPF.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:SQL_Application_WPF"
        mc:Ignorable="d"
        Title="MainWindow" Height="558.579" Width="641.957">
    <Grid>
        <Label Content="Zoo List" HorizontalAlignment="Left" Margin="30,10,0,0" VerticalAlignment="Top" Width="140" Height="33"/>
        <ListBox Name="ZooList" HorizontalAlignment="Left" Height="210" Margin="30,48,0,0" VerticalAlignment="Top" Width="140"/>
    </Grid>
</Window>

C# code:

using System;
using System.Windows;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace SQL_Application_WPF
{
    public partial class MainWindow : Window
    {
        SqlConnection sqlConnection;

        public MainWindow()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["SQL_Application_WPF.Properties.Settings.SQLAppLearningConnectionString"].ConnectionString;

            sqlConnection = new SqlConnection(connectionString);

            ShowZoos();
        }

        private void ShowZoos()
        {
            try
            {
                string query = "SELECT * FROM Zoo";

                // The SqlDataAdapter can be imagined to be a sort of an interface to make Tables usable by C# Objects
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);

                using (sqlDataAdapter)
                {
                    DataTable zooTable = new DataTable();
                    sqlDataAdapter.Fill(zooTable);

                    //Information that will be displayed in the List Box from the Table in DataTable. 
                    ZooList.DisplayMemberPath = "Location";

                    //Value that will be delivered when an item from the List Box is selected
                    ZooList.SelectedValuePath = "Id";

                    //The reference to the DataTable should populate.
                    ZooList.ItemsSource = zooTable.DefaultView;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
    }
}

When I run this code, I get a System.NullReferenceException on the following line:

ZooList.DisplayMemberPath = "Location";

I can't figure out what's causing this. I've made sure that the name of the column is properly matched as well but since my knowledge at the moment is at a very beginning stage, I don't know what could be the cause of this.

I'll really appreciate any feedback or input.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

3 Answers3

2

Try this:

      SqlConnection sqlConnection;
        public MainWindow()
        {

            string connectionString = ConfigurationManager.ConnectionStrings["SQL_Application_WPF.Properties.Settings.SQLAppLearningConnectionString"].ConnectionString;
            sqlConnection = new SqlConnection(connectionString);
            
            InitializeComponent(); //readies the controls in the visual tree so your code can access them properly, avoiding null ref errors

            ShowZoos();

        }
DavidG
  • 113,891
  • 12
  • 217
  • 223
Tore Aurstad
  • 3,189
  • 1
  • 27
  • 22
1

This is a problem of not having proper debugging skills. In this case, I'm guessing ZooList is null.

I'm assuming you are using Visual Studio. Is that correct?

Here is how you pinpoint any exception in Visual Studio.

  1. Bring up the Exception Settings Window (Debug >> Windows >> Exception Settings)
  2. Find the name of the exception you're looking for. In a managed application, it will probably be undernath "Common Language Runtime Exceptions" Try typing it into the Search Box. In this case, type"NullRef". That will bring up "System.NullRefererenceException" Make sure that is checked.
  3. Run a Debug build of the application. Do whatever you have to do to make the problem happen. The debugger will stop at the very moment the exception is thrown.
  4. Look at the 'Autos" or "Locals" Debugger windows. Examine the values of all the variables going into the call. One of them will be null when it should not be
  5. Either spot the reason (in that function) why the value that should not be null, is null, or, if it is a parameter passed into the function, bring up the call-stack window and start clicking one level up and up again until you find the source of the function that generated that null parameter.
Joe
  • 5,394
  • 3
  • 23
  • 54
0

When MainWindow() is being callled, the UI elements are not ready yet, i.e. the ZooList has not been created yet. To solve this problem, you should query the database and set the UI elements after window is loaded, which is indicated by a Loaded event.

xaml

<Window x:Class="SQL_Application_WPF.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:SQL_Application_WPF"
    mc:Ignorable="d"
    Title="MainWindow" Height="558.579" Width="641.957"
    Loaded="Window_Loaded"
    >

code behinded

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    ShowZoos();
} 
mwck46
  • 148
  • 9