Created
November 27, 2015 11:29
-
-
Save potatoqualitee/dc5cbaecc04ce2a60e85 to your computer and use it in GitHub Desktop.
WPF + PowerShell + SQL super simple example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Load WPF Assemblies | |
Add-Type -AssemblyName PresentationFramework | |
# Get the info you need from SQL Server | |
$sqlserver = "sqlserver2014a" | |
$query = "select name from master.dbo.sysdatabases order by name" | |
$conn = New-Object System.Data.SqlClient.SqlConnection | |
$conn.ConnectionString = "Data Source=$sqlserver;Integrated Security=True;Connection Timeout=3" | |
$conn.Open() | |
$cmd = New-Object System.Data.SqlClient.SqlCommand($query, $conn, $null) | |
$datatable = New-Object System.Data.DataTable | |
$datatable.Load($cmd.ExecuteReader()) | |
$itemsource = $datatable.rows.name | |
$cmd.Dispose() | |
$conn.Close() | |
$conn.Dispose() | |
# Create the Window | |
[xml]$script:xaml = '<Window | |
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" | |
Title="PowerShell + WPF + SQL" Height="200" Width="425"> | |
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center"> | |
<Label Name="message"/> | |
<Grid> | |
<Grid.ColumnDefinitions> | |
<ColumnDefinition Width="Auto"/> | |
<ColumnDefinition Width="Auto"/> | |
</Grid.ColumnDefinitions> | |
<Label Content="Database:" Grid.Column="0" /> | |
<ComboBox Name="dbComboBox" Grid.Column="1" Width="120"/> | |
</Grid> | |
</StackPanel> | |
</Window>' | |
# Turn XAML into PowerShell objects | |
$window = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml)) | |
$xaml.SelectNodes("//*[@Name]") | ForEach-Object { Set-Variable -Name ($_.Name) -Value $window.FindName($_.Name) -Scope Script } | |
# Populate combobox with database names | |
$dbComboBox.ItemsSource = $itemsource | |
# Add an event to work with the form | |
$dbComboBox.Add_DropDownClosed({ | |
$message.Content = "You selected: $($dbComboBox.Text)" | |
}) | |
# Show form | |
$window.ShowDialog() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment