【问题标题】:WPF C# DataGrid binding to a stored procedureWPF C# DataGrid 绑定到存储过程
【发布时间】:2021-09-19 07:43:46
【问题描述】:

我是 WPF C# 开发的新手……非常擅长 SSIS/SSRS,但这个让我很吃惊。最终,我试图在 DataGrid 中显示存储过程中的数据表。我可以让它适用于单个表,但是存储过程连接了许多表并且有一个我需要传入的日期参数。我很感激你能给我的任何方向 - 那里似乎几乎没有任何指示如何做这很容易。

首先,这是我获取连接字符串的方式。我使用“添加新项目”在我的项目中添加了一个 ADO.NET 实体数据模型:

我正在检查所有存储过程和表,我将其命名为PlacementInvoicesEntities

这是app.config 的内容:

<connectionStrings>
    <add name="PlacementInvoicesEntities" 
         connectionString="metadata=res://*/PlacementData.csdl|res://*/PlacementData.ssdl|res://*/PlacementData.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MYSERVER;initial catalog=PlacementInvoices;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" 
         providerName="System.Data.EntityClient" />
</connectionStrings>

适用于单个表的我的 XAML 如下:

<DataGrid Grid.Column="1" Grid.Row="4" Grid.ColumnSpan="3" 
              Name="PermInvoices" 
              AutoGenerateColumns="False"
              ItemsSource="{Binding}"
              CanUserResizeRows="False"
              CanUserAddRows="False"
              FrozenColumnCount="2">
        <DataGrid.Columns>
        <DataGridTextColumn Header="Invoice #" Binding="{Binding Path=InvoiceNum}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Placement #" Binding="{Binding Path=PlacementNum}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Date Loaded" Binding="{Binding Path=dateLoaded}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Approval Sent" Binding="{Binding Path=ApprovalEmailSent}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Status" Binding="{Binding Path=Status}"/>
        <DataGridTextColumn Header="Approver Email" Binding="{Binding Path=ApproverEmail}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Billing Email" Binding="{Binding Path=billingEmail}" IsReadOnly="True"/>
        </DataGrid.Columns>
    </DataGrid>

在页面后面的代码中,我有这个 - 它仅适用于该表 PermAutomation_Log,但我想为存储过程工作,我们称它为 spPermLog 并带有日期参数 @ApprovalDate:

private void DispData_Click(object sender, RoutedEventArgs e)
{
    try
    {
        PlacementInvoicesEntities conn = new PlacementInvoicesEntities();

        List<PermAutomation_Log> TableData = conn.PermAutomation_Log.ToList();
        PermInvoices.ItemsSource = TableData;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

我在页面上有一个名为“DateLoaded”的 datePicker,我想将它输入到存储过程参数中。我已经尝试了所有我能想到的方法,我什至无法获得一个没有参数的存储过程。

谢谢!

【问题讨论】:

  • 我应该补充一下——如果你想知道为什么我不会在 SSRS 中这样做,因为现在它实际上只是一个报告——这是因为我需要交互界面。我需要最终用户能够将特定值更新回 SQL 表。所以在我加载完这个之后,我的下一个挑战是让从这个界面更新记录成为可能。
  • 为什么不将查询设为视图并将其用作普通的只读表?甚至在 .NET 中为连接编写 LINQ,而不是将其放在 SP 中
  • 如果没有,请查看c-sharpcorner.com/UploadFile/ff2f08/…
  • SP是如何定义的?它返回/选择什么?
  • @fredrik - 我可能可以将查询设为视图,我只需要指定一个 WHERE 子句。但是伙计-我认为c-sharpcorner链接就是它。我现在就试试看。

标签: c# sql-server wpf


【解决方案1】:

好吧,在继续研究将 SQL 与 WPF DataGrid 绑定的方法后,我得到了它。这就是它对我有用的方式。也许它会帮助像我这样的其他新手。

首先,我显然想多了连接字符串。我所需要的只是 app.config 中的一个简单连接字符串:

<connectionStrings>
<add name="PlacementInvoices" connectionString="Data Source=SERVERNAME;initial catalog=PlacementInvoices;integrated security=True"/> 

然后我就能够使用 SQLCommand 构建一个查询字符串,并将它绑定到我的表。这甚至适用于我的 DatePicker。

private void DispData_Click(object sender, RoutedEventArgs e)
    {
        DateTime? SelectedDate = DateLoaded.SelectedDate;
        
        string ConString = ConfigurationManager.ConnectionStrings["PlacementInvoices"].ConnectionString;
        string CmdString = string.Empty;

        CmdString = "exec ssrs_DHAutomationLog '" + SelectedDate.Value.ToString("MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture) + "'";

        try
        {
            using (SqlConnection con = new SqlConnection(ConString))
            {
                SqlCommand cmd = new SqlCommand(CmdString, con);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable("Invoices");
                sda.Fill(dt);
                PermInvoices.ItemsSource = dt.DefaultView;
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

This is the article that helped me out

【讨论】:

  • aahhhgggg... 不要连接命令字符串。了解如何参数化您的查询...查看 SqlCommandParameter()。不同的数据库使用不同的字符来表示参数。 @ 用于 sqlserver,:用于 sqlite,?对于其他人作为未命名的参数占位符,并且每个参数需要以相同的顺序添加?用过等等。
  • 谢谢@DRapp 我猜旧习惯很难改掉。我将研究 SqlCommandParameter()。感谢您的提示。
猜你喜欢
  • 2013-06-20
  • 1970-01-01
  • 2017-05-13
  • 2017-04-16
  • 2011-03-27
  • 2023-04-02
  • 2022-12-17
  • 2013-10-14
  • 2011-05-14
相关资源
最近更新 更多