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.