DataGridView - Hide Column

I’m using WinForms with PS to create a DataGridView. I’m pulling data from a SQL table and have a column that’s called “ID” that’s a Primary Key and is auto incrementing. I’m trying to hide that column.

$CertGrid = New-Object system.Windows.Forms.DataGridView
$CertGrid.width = 1275
$CertGrid.height = 450
$CertGrid.location = New-Object System.Drawing.Point(20,20)
$CertGrid.BackColor = [System.Drawing.ColorTranslator]::FromHtml("#ffffff")
$CertGrid.TabIndex = 1
$CertGrid.add_CurrentCellDirtyStateChanged($CertGrid_CurrentCellDirtyStateChanged)
$CertGrid.RowHeadersVisible = $TRUE
$CertGrid.defaultCellStyle.wrapMode= [System.Windows.Forms.DataGridViewTriState]::True
$CertGrid.AutoSizeRowsMode = [System.Windows.Forms.DataGridViewAutoSizeRowsMode]::AllCells
$CertGrid.AutoSizeColumnsMode = [System.Windows.Forms.DataGridViewAutoSizeColumnsMode]::AllCells
$CertGrid.AllowUserToDeleteRows = $TRUE
$CertGrid.AutoGenerateColumns = $TRUE

I’ve tried
$CertGrid.Columns["ID"].Visible = $FALSE and also [0], which is the Display Index. I’m getting the following error: The property ‘Visible’ cannot be found on this object. Verify that the property exists and can be set.

You need to use a DataBindingComplete event handler:

$dataBindingComplete = {
    param ([object]$sender, [System.EventArgs]$e) 
        $CertGrid.Columns['Column1'].Visible = $false
}

$form.Add_load($dataBindingComplete)

Full test code:

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Data

$dataTable = New-Object System.Data.DataTable

$range = 1..3

foreach ($r in $range) {
    $column = $dataTable.Columns.Add("Column$r")    
}

$form = New-Object System.Windows.Forms.Form

$CertGrid = New-Object system.Windows.Forms.DataGridView
$CertGrid.width = 1275
$CertGrid.height = 450
$CertGrid.location = New-Object System.Drawing.Point(20,20)
$CertGrid.BackColor = [System.Drawing.ColorTranslator]::FromHtml("#ffffff")
$CertGrid.TabIndex = 1
$CertGrid.add_CurrentCellDirtyStateChanged($CertGrid_CurrentCellDirtyStateChanged)
$CertGrid.RowHeadersVisible = $TRUE
$CertGrid.defaultCellStyle.wrapMode= [System.Windows.Forms.DataGridViewTriState]::True
$CertGrid.AutoSizeRowsMode = [System.Windows.Forms.DataGridViewAutoSizeRowsMode]::AllCells
$CertGrid.AutoSizeColumnsMode = [System.Windows.Forms.DataGridViewAutoSizeColumnsMode]::AllCells
$CertGrid.AllowUserToDeleteRows = $TRUE
$CertGrid.AutoGenerateColumns = $TRUE
$CertGrid.DataSource = $dataTable

$dataBindingComplete = {
    param ([object]$sender, [System.EventArgs]$e) 
        $CertGrid.Columns['Column1'].Visible = $false
}

$form.Add_load($dataBindingComplete)
$form.Controls.Add($CertGrid)
$form.ShowDialog()
1 Like

Thank you, sir! That worked!