【发布时间】:2021-10-16 06:19:44
【问题描述】:
我一直在学习 C#,并且一直在观看 Udemy 课程。我对 SQL 的了解非常有限。我正在观看一场讲座,现在我正在按照步骤制作一个简单的 WPF 应用程序,该应用程序将显示来自两个表的数据,并让我添加、删除或更新两个表中的数据。
代码如下:
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">
<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#代码:
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());
}
}
}
}
当我运行这段代码时,我在下面一行得到一个System.NullReferenceException:
ZooList.DisplayMemberPath = "Location";
我不知道是什么原因造成的。我已经确保列的名称也正确匹配,但由于我目前的知识还处于起步阶段,我不知道这可能是什么原因。
非常感谢任何反馈或意见。
【问题讨论】:
-
尝试添加 InitializeComponent(); ShowZoos() 之前;重建并再次运行。成功了吗?
标签: c# sql-server wpf