Search code examples
c#sql-serverwpfwpfdatagrid

Binding SQL data to a datagrid


Trying to get data from a SQL database to be displayed in a datagrid and it is not being displayed.

Code is as follows:

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();
        }
    }

EDIT UP: end-quote was missing in sql query.

I have a SQL database with data inside it but i am unsure of how to get the datagrid to display it, as this should work. Unless i have forgotten to add something. The grid must show data on load.

EDIT: Datagrid Code

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

Solution

  • I ended up abandoning datagrid and opted for listview instead which i managed to get working rather quickly and it displays the data from SQL on window load.

    I added:

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

    Removed the GetDataTable function.