PowerShell/WinForms - Row Header

2016/07/28 | 1 minute read |

If you are creating Windows Forms (WinForms) using PowerShell with tools such as PowerShell Studio from Sapien, you might have some scenario where you want to use Row Header instead of Column Header in a DataGridView control.

Those can be controlled using the properties RowHeaderVisible and ColumnHeaderVisible.

Assuming you already have a form with a Datagridview in it, you will need to do the following:

  • Create a Column
  • Create a Row with the Header value (and optionally a value for the first column)
  • Add the Row to the DataGridView
  • Set RowHeaderVisible to $true
  • Set ColumnHeaderVisiable to $false (Optional)

(The example can be download on my github)

Creating a Column

# Create Column object
$NewColumn = New-Object -TypeName System.Windows.Forms.DataGridViewTextBoxColumn
$NewColumn.Name = "Column1"
$NewColumn.HeaderText = "Column1"

# Add the Column to the Datagridview
$DataGridView.Columns.Add($NewColumn)

Creating a Row with Header value

# Create a Row
$Row = New-Object -TypeName System.Windows.Forms.DataGridViewRow

# Set a Row Header value
$Row.HeaderCell.Value = "Header1"

# Set the Header and a row value (for the first column)
$Row.CreateCells($DataGridView, "Value1")

Add Row to Datagridview

# Add the row to the DataGridView control
$DataGridView.Rows.Add($Row)

Hide the Column Header and Show the Row Header

# Make the Row Header Visible
$DataGridView.RowHeadersVisible = $true

# Make the Column Header Invisible
$DataGridView.ColumnHeadersVisible = $false

Easy way: Using the PowerShell module WinFormPS

I started a Window Forms module a while ago called WinFormPS. This module allows you to interact with WinForms control using PowerShell. The module is available on GitHub here: https://github.com/lazywinadmin/WinFormPS

For our case here, you can either use the entire module or just copy the functions you need in your module.

Performing the same steps is way easier:

# Add Column
Add-WFDataGridViewColumn -DataGridView $datagridview1 -ColumnName "First Column"

# Add Row and Row Header
Add-WFDataGridViewRow -DataGridView $datagridview1 -Title "Header1" -Values "Value1"

# Set the Row Header to Visible
Set-WFDataGridView -DataGridView $datagridview1 -ShowRowHeader

# Set the Column Header to Invisible
Set-WFDataGridView -DataGridView $datagridview1 -HideColumnHeader

Download this example

Leave a Comment