PowerShell finally loves DataGrid

Posted by

The first time I wanted to manipulate the DataGrid with Powershell it took me some time to get it to work. So I just want to share how I did this and continue to work on the example from my last post.

First we need to setup the DataGrid with some columns and header bindings. When that is done we need to create a button we can push and an click event for that button . So when the button is pushed the content is added to the DataGrid, and that is the tricky part since it is a DataGrid and I found a nice way to use Add-Member that is understandable as well.

 

Ok so time to do it, open up the .XAML file and locate the DataGrid Tag below

<DataGrid HorizontalAlignment=”Left” Margin=”10,10,0,0″ VerticalAlignment=”Top” Height=”146″ Width=”475″>
</DataGrid>

And edit it to look something like this

<DataGrid Name=”dg_Log” Margin=”2,2,2,2″ >
  <DataGrid.Columns>
    <DataGridTextColumn Header=”H1″ Binding=”{Binding H1}” Width=”SizeToCells” />
    <DataGridTextColumn Header=”H2″ Binding=”{Binding H2}” Width=”SizeToCells” />
    <DataGridTextColumn Header=”H3″ Binding=”{Binding H3}” Width=”SizeToCells” />
    <DataGridTextColumn Header=”H4″ Binding=”{Binding H4}” Width=”*” />
  </DataGrid.Columns>
</DataGrid>

Also add content and a name to one of the buttons

<Button Content=”Add row” Name=”btn_1″ Width=”125″ Grid.Column=”1″ Margin=”2,2,2,2″ HorizontalAlignment=”Center” VerticalAlignment=”Center” />

In the .PS1 file add these rows where appropriate

$btn_1 = $mainform.FindName(‘btn_1’)

$btn_1.Add_Click({
    $row= New-Object PSObject
    Add-Member -inputObject $row -memberType NoteProperty -name “H1” -value “First column”
    Add-Member -inputObject $row -memberType NoteProperty -name “H4” -value “Fourth”
    Add-Member -inputObject $row -memberType NoteProperty -name “H2” -value “Second”
    Add-Member -inputObject $row -memberType NoteProperty -name “H5” -value “This will not show”

    $dg_Log.AddChild($row)
})

I did some more customizations and it looks like this when I press “Button 1”

image

Advertisements

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.