1

我正在尝试从我的数据库中的“PurchaseTable”表中搜索购买并在 DataGrid 中显示结果,我知道如何使用 Windows 窗体进行操作:

private void SearchButton_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        SqlDataAdapter SDA = new SqlDataAdapter("SELECT TitleOfRecord, DateOfPurchase FROM  PurchaseTable WHERE (NameOfCustomer = '"+NameOfCustomerSText.Text+"')", connection);
        //Query that will return the Title of the Records and Dates of purchases depending on the Customer which has been searched for
        SDA.Fill(dt);
        PurchaseResults.DataSource = dt;
        //Results will appear in the PurchaseResults DataGrid
    }

但我不知道如何用 WPF 做到这一点,到目前为止我有这个但它不起作用:

private void SearchCustomerButton_Click(object sender, RoutedEventArgs e)
    {
        DataTable dt = new DataTable();
        SqlDataAdapter SDA = new SqlDataAdapter("SELECT TitleOfRecord, DateOfPurchase FROM  PurchaseTable WHERE (NameOfCustomer = '" + NameOfCustomerSText.Text + "')", connection);
        //Query that will return the Title of the Records and Dates of purchases depending on the Customer which has been searched for
        SDA.Fill(dt);
        PurchaseResults.DataContext = dt;
        //Results will appear in the PurchaseResults DataGrid
    }

我有这些命名空间:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.Data.SqlClient;
using System.Data;

我用这段代码来解决我的问题:

private void SearchCustomerButton_Click(object sender, RoutedEventArgs e)
    {
        SqlDataAdapter da;
        DataSet ds;
        da = new SqlDataAdapter("SELECT TitleOfRecord, DateOfPurchase FROM  PurchaseTable WHERE (NameOfCustomer = '" + NameOfCustomerSText.Text + "')", connection);
        //Query that will return the Title of the Records and Dates of purchases depending on the Customer which has been searched for
        ds = new DataSet();
        da.Fill(ds);
        PurchaseResults.ItemsSource = ds.Tables[0].DefaultView;
        //Results will appear in the PurchaseResults DataGrid
    }
4

4 回答 4

1

改变

PurchaseResults.DataContext = dt;

PurchaseResults.ItemsSource = dt;
于 2013-04-24T15:22:32.950 回答
1

您是否定义了数据网格中的列。如果不是,当您将 AutoGenerateColumns 属性设置为 true 时,WPF 可以自动为您生成它。

PurchaseResults.AutoGenerateColumns = true;
PurchaseResults.ItemsSource = dt;
于 2013-04-24T15:27:59.500 回答
1

当您使用后面的代码时,您应该提供 DataGrid ItemSouce,但在使用 MVVM 架构处理绑定时,DataContext则使用。

所以更换

PurchaseResults.DataContext = dt;

PurchaseResults.ItemsSource = dt;
于 2013-04-24T15:31:05.563 回答
1

你可以试试

PurchaseResults.ItemsSource = dt.AsDataView();
于 2013-04-24T15:43:34.523 回答