gpt4 book ai didi

c# - 如何使用 WPF 搜索数据库并将结果显示在 DataGrid 中

转载 作者:太空宇宙 更新时间:2023-11-03 21:47:30 26 4
gpt4 key购买 nike

我正在尝试从我的数据库中的“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
}

最佳答案

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

所以替换

PurchaseResults.DataContext = dt;

PurchaseResults.ItemsSource = dt;

关于c# - 如何使用 WPF 搜索数据库并将结果显示在 DataGrid 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16195869/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com