【问题标题】:Binding SQL data to a datagrid将 SQL 数据绑定到数据网格
【发布时间】:2014-08-04 10:43:11
【问题描述】:

试图从 SQL 数据库中获取数据以显示在数据网格中,但未显示。

代码如下:

using System;
using System.Windows;
using System.Data.SqlClient;

namespace Data
{

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    string SQLSERVER_ID = @""; - Removed the ID and Password intentionally to show this code.
    string SQLDatabaseName = "Data Logging";
    string SQLServerLoginName = "Data User";
    string SQLServerPassword = "";

    public void SQLCmd(string SQLString)
    {
        try
        {
            SqlConnection conDatabase = new SqlConnection(String.Format(@"Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLSERVER_ID, SQLDatabaseName, SQLServerLoginName, SQLServerPassword));
            conDatabase.Open();
            SqlCommand cmdDatabase = new SqlCommand("INSERT INTO Bags (RecordNumber, Date, Time) VALUE ('1', '2014-08-01', '08:00:00')" + SQLString, conDatabase);
            cmdDatabase.ExecuteNonQuery();
            conDatabase.Close();
            conDatabase.Dispose();
        }
        catch (Exception em)
        {
            MessageBox.Show(em.ToString());
        }

    }

    public System.Data.DataTable GetDataTable(string SQLString)
    {
        try
        {
            System.Data.DataTable dtTable = new System.Data.DataTable("dtTable");
            string ConnectionString = String.Format(@"Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLSERVER_ID, SQLDatabaseName, SQLServerLoginName, SQLServerPassword);
            SqlDataAdapter sqlAdpt = new SqlDataAdapter("SELECT * FROM bags ORDER BY RecordNumber, Date, Time", ConnectionString);
            sqlAdpt.Fill(dtTable);
            sqlAdpt.Dispose();
            return dtTable;
        }
        catch (Exception em)
        {

            MessageBox.Show(em.ToString());
            return new System.Data.DataTable();
        }
    }

编辑:sql 查询中缺少尾引号。

我有一个 SQL 数据库,其中包含数据,但我不确定如何让数据网格显示它,因为这应该可以工作。除非我忘记添加一些东西。网格必须显示负载数据。

编辑:数据网格代码

<DataGrid Name="dtTable" Margin="0,64,0,0" AutoGenerateColumns="True"    VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" CanUserResizeColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="_Record Number" Binding="{Binding RecordNumber}"/>
                <DataGridTextColumn Header="_Date" Binding="{Binding Date}"/>
                <DataGridTextColumn Header="_Time" Binding="{Binding Time}"/>                   
            </DataGrid.Columns>
        </DataGrid>

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
    <add name="Bags_Data.Properties.Settings.BagsConnectionString"
        connectionString="Data Source=*****;Initial Catalog=&quot;Bags&quot;;User ID=***;Password=*****"
        providerName="System.Data.SqlClient" />
</connectionStrings>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

【问题讨论】:

  • 你有没有试过把这个结果绑定到你的.DataSource属性中?
  • 您的 DataGrid 绑定代码在哪里?
  • 已编辑。我不相信它正在与数据库建立连接,因为它里面有记录。
  • @zen_1991 您应该在后面的代码中将数据绑定到数据网格。
  • 谢谢你试试看!

标签: c# sql-server wpf wpfdatagrid


【解决方案1】:

看起来您假设因为 DataGrid 被称为 dtTable 而您的 System.Data.DataTable 被称为 dtTable,所以幕后的某些东西将为您连接这两者,或者它们以某种方式相互引用。不是这种情况。您将需要在 Load 上实现代码,该代码将调用您的 GetDataTable 函数,将结果 DataTable 设置为等于 DataGrid 的 ItemSource 属性。您还应该使用 ViewModel 研究 Binding。

【讨论】:

    【解决方案2】:

    我建议你做的是重命名你的数据网格,这样事情会更容易看到:

    <DataGrid Name="RecordsDataGrid" Margin="0,64,0,0" AutoGenerateColumns="True"    VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" CanUserResizeColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="_Record Number" Binding="{Binding RecordNumber}"/>
                <DataGridTextColumn Header="_Date" Binding="{Binding Date}"/>
                <DataGridTextColumn Header="_Time" Binding="{Binding Time}"/>                   
            </DataGrid.Columns>
        </DataGrid>
    

    在你后面的代码中,创建一个记录列表并使用 dataAdapter 用你的表中的数据填充它,然后你可以将它绑定到你的数据网格:

    RecordsDataGrid.ItemsSource = YourListOfRecords;
    

    【讨论】:

      【解决方案3】:

      我最终放弃了 datagrid 并选择了 listview 代替,我设法相当快地开始工作,它在窗口加载时显示来自 SQL 的数据。

      我补充说:

      private void Window_Loaded(object sender, RoutedEventArgs e)
          {
              ShowData();
          }
      
          private void ShowData()
          {
              SqlConnection con = new SqlConnection(String.Format(@"Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLSERVER_ID, SQLDatabaseName, SQLServerLoginName, SQLServerPassword));
              con.Open();
              SqlCommand comm = new SqlCommand("SELECT * FROM Bags", con);
              DataTable dt = new DataTable();
              SqlDataAdapter da = new SqlDataAdapter(comm);
              da.Fill(dt);
              listView1.DataContext = dt.DefaultView;
          }
      

      删除了 GetDataTable 函数。

      【讨论】:

        猜你喜欢
        • 2016-11-13
        • 1970-01-01
        • 1970-01-01
        • 2011-01-31
        • 2017-05-14
        • 2012-12-25
        • 2013-03-28
        • 1970-01-01
        • 2013-12-30
        相关资源
        最近更新 更多