我正在尝试从我的数据库中搜索购买,从“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
}
答案 0 :(得分:1)
更改
PurchaseResults.DataContext = dt;
到
PurchaseResults.ItemsSource = dt;
答案 1 :(得分:1)
您是否在数据网格中定义了列。如果不是,当您将AutoGenerateColumns属性设置为true时,WPF可以自动为您生成它。
PurchaseResults.AutoGenerateColumns = true;
PurchaseResults.ItemsSource = dt;
答案 2 :(得分:1)
当您使用代码时,您应该提供DataGrid的ItemSouce
,但在处理Binding与MVVM架构时,则使用DataContext
。
所以替换
PurchaseResults.DataContext = dt;
到
PurchaseResults.ItemsSource = dt;
答案 3 :(得分:1)
你可以尝试
PurchaseResults.ItemsSource = dt.AsDataView();