将SQL数据绑定到数据网格

时间:2014-08-04 10:43:11

标签: c# sql-server wpf wpfdatagrid

尝试从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>

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

<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;

答案 2 :(得分:0)

我最终放弃了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函数。