title: How to get SQL data into a WPF DataGrid using powershell?
body: <p>I am trying to add my sql query data into WPF powershell application. In <code>$dg</code> items I see my computer names which are being returned by the SQL query, but m datagrid isn't getting populated.</p>
  
  <p>Here's my code</p>
  
  <pre><code>function Invoke-sql1
  {
      param( [string]$sql,
          [System.Data.SQLClient.SQLConnection]$connection
      )
  
      $cmd = new-object System.Data.SQLClient.SQLCommand($sql,$connection)
      $ds = New-Object system.Data.DataSet
      $da = New-Object System.Data.SQLClient.SQLDataAdapter($cmd)
      $da.fill($ds) | Out-Null
      return $ds.tables[0].rows
  }
  
  
  [xml] $xaml = @"
  &lt;Window 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="MainWindow" Height="350" Width="525"&gt;
  &lt;Grid&gt;
  &lt;DataGrid 
      AutoGenerateColumns="False" 
      HorizontalAlignment="Left" 
      Name="dataGrid1" 
      VerticalAlignment="Top" 
      Width="330"
      HeadersVisibility="All" 
      &gt;
      &lt;DataGrid.Columns&gt;
          &lt;DataGridTextColumn Header="SystemName"
                      Binding="{Binding SystemName}" 
                      /&gt;
          &lt;DataGridTextColumn Header="ProcessorLoad"
                      Binding="{Binding ProcessorLoad}" 
                      /&gt;
          &lt;DataGridTextColumn Header="CreatedDate"
                      Binding="{Binding CreatedDate}" 
                      /&gt;
      &lt;/DataGrid.Columns&gt;
  &lt;/DataGrid &gt;
  &lt;/Grid&gt;
  &lt;/Window&gt;
  "@
  
  $reader=(New-Object System.Xml.XmlNodeReader $xaml)
  $Form=[Windows.Markup.XamlReader]::Load( $reader )
  
  
  $con = New-Object System.Data.SqlClient.SqlConnection
  $con.ConnectionString=@"
  DataSource=JAPDC\SQLEXPRESS;
  IntegratedSecurity=True;
  Initial Catalog=TestDB;
  "@
  $con.open()
  
  $sql = “​SELECT t1.SystemName, t1.ProcessorLoad, t1.CreatedDate
  FROM   [TestDB].[dbo].[CPUPerformance] t1
     INNER JOIN (SELECT Max(CreatedDate) CreatedDate, SystemName
                 FROM   [TestDB].[dbo].[CPUPerformance] 
  
                GROUP BY [TestDB].[dbo].[CPUPerformance].SystemName ) AS t2 
       ON 
           t1.SystemName = t2.SystemName
           and t1.CreatedDate = t2.CreatedDate 
  ORDER  BY CreatedDate DESC ”
  
  $dg = $Form.FindName("dataGrid1")
  $dg.ItemsSource = @(Invoke-sql1 $sql $con)
  $dg
  $Form.ShowDialog()
  </code></pre>
  
  <p>If there is another way to do it, let me know.</p>