C# 将搜索结果显示到DataGrid中

C# 将搜索结果显示到DataGrid中,c#,wpf,C#,Wpf,我一直在试图找出这个错误: Toys Live.exe中首次出现类型为“System.NullReferenceException”的异常 其他信息:对象引用未设置为对象的实例 这是产生上述错误的代码字符串: DataRow[] returnRows = DS.Tables["Product"].Select("Typeoftoy='" + searchOut + "'"); 对象引用应该是下面的代码,除非我遗漏了其他内容 public partial class MainWindow : W

我一直在试图找出这个错误:

Toys Live.exe中首次出现类型为“System.NullReferenceException”的异常 其他信息:对象引用未设置为对象的实例

这是产生上述错误的代码字符串:

DataRow[] returnRows = DS.Tables["Product"].Select("Typeoftoy='" + searchOut + "'");
对象引用应该是下面的代码,除非我遗漏了其他内容

public partial class MainWindow : Window
{
    private SqlDataAdapter dAdapter = new SqlDataAdapter();
    private DataSet DS = new DataSet();
    private SqlConnection conConnect;

    public MainWindow()
    {
        InitializeComponent();
    }
这是我目前正在使用的代码块,用于在WPF中将文本框中的搜索结果显示到数据网格中

private void SearchBTN_Click(object sender, RoutedEventArgs e)
    {
        conConnect = new SqlConnection("Data Source=GERRY;Initial Catalog=toyDB;Integrated Security=True");

        dAdapter = new SqlDataAdapter("SELECT Typeoftoy   FROM Product", conConnect);
        DS = new DataSet();

        if (tbSearch.Text.Length >= 1)
        {
            string searchOut = tbSearch.Text;
            int result = 0;

            dAdapter.Fill(DS, "MyDataBinding");

            DataRow[] returnRows = DS.Tables["Product"].Select("Typeoftoy='" + searchOut + "'");

            result = returnRows.Length;

            if (result > 0)
            {
                datagrid1.ItemsSource = returnRows.CopyToDataTable().DefaultView;
            }
            else
            {
                MessageBox.Show("No Records Found");
            }

            conConnect.Close();
        }
    }

空引用异常意味着您正试图使用一个对象,该对象现在已用“新”构造实例化。目前尚不清楚是什么一系列事件导致了这一现象。查看获取异常的那一行,您会发现抛出异常的方法所在的类没有实例化。在使用代码之前,请仔细检查代码,并确保使用“new”对其进行实例化。

我认为您的SQL查询有问题,并且没有正确填充数据集,然后尝试访问表属性,如果查询没有按预期工作,表属性可能为null


为dAdapter.Fill方法设置一个断点,并确保它输出预期的结果

我已经解决了问题这里是问题,然后是解决方案:

问题出在DS中。Tables[“Product”]使用数据集中的索引而不是名称访问该表

DataRow[] returnRows = DS.Tables["Product"].Select("Typeoftoy='" + searchOut + "'");
解决方案是删除[“产品”]并将其索引设置为0

 DataRow[] returnRows = DS.Tables[0].Select("Typeoftoy='" + searchOut + "'");

当我使用dAdapter.Fill(DS,“MyDataBinding”);在按钮单击事件填充DataGrid期间,它工作正常。它从DB表中检索数据,并用我在列中输入的数据填充网格。然后哪一行抛出NullReferenceException这里是代码行::DataRow[]returnRows=DS.Tables[“Product”]。选择(“TypeofToy=”+“searchOut+”);错误代码行:DataRow[]returnRows=DS.Tables[“Product”]。选择(“TypeofToy=”+“searchOut+”);这里是您正在谈论的“新”数据集DS=new DataSet();这仅声明为my dAdapter=new SqlDataAdapter line code下的一行。由于您正在声明新对象,因此对
表[“Product”]
的调用可能不会返回任何内容。您可以尝试通过索引访问它,或者可能是“产品”的拼写不符合预期。