Home > Software design >  Powershell linking datagridview to an array
Powershell linking datagridview to an array

Time:09-30

I am currently trying to load a json file that is a DB into a datagridview within a form. I currnetly have the JSON file loading into an array. What I cant figure out is how to get the array to load into the datagridview so I can display the data of what is in said array from within the form.

I dont think im too far off any help would be much appreciated.

#JSON DB Front end
$jsonDB = Get-Content 'C:\Support\HardwareCollection.json' | Out-String | ConvertFrom-Json
#jsonDb has $jsonDB.Date and $jsonDB.username

$Form = New-Object system.Windows.Forms.Form 
$Form.Size = New-Object System.Drawing.Size(1050,425) 
$form.MaximizeBox = $false 
$Form.StartPosition = "CenterScreen" 
$Form.FormBorderStyle = 'Fixed3D' 
$Form.Text = "Hardware Collection"
$dataGridView = New-Object System.Windows.Forms.DataGridView
$dataGridView.Size=New-Object System.Drawing.Size(500,200)
$dataGridView.Location = new-object system.drawing.size(1,150)
$dataGridView.ColumnCount = 2
$dataGridView.Columns[0].Name = "Date"
$dataGridView.Columns[1].Name = "Username"
$form.Controls.Add($dataGridView)  

$datagridview.DataSource = $jsonDB

$Form.ShowDialog()

Many thanks!!!

CodePudding user response:

You're right - you were close - the dataGridView likes .NET types for its data sources, not Powershell objects. So, just create an ArrayList from your Powershell collection, and it works:

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

$jsonDB = Get-Content 'C:\Support\HardwareCollection.json' | Out-String | ConvertFrom-Json
$tableData = New-Object System.Collections.ArrayList
$tableData.AddRange($jsonDB)

$Form = New-Object System.Windows.Forms.Form 
$Form.Size = New-Object System.Drawing.Size(1050, 425) 
$Form.MaximizeBox = $False 
$Form.StartPosition = "CenterScreen" 
$Form.FormBorderStyle = 'Fixed3D' 
$Form.Text = "Hardware Collection"

$dataGridView = New-Object System.Windows.Forms.DataGridView -Property @{
    Size = New-Object System.Drawing.Size(500, 200)
    Location = New-Object System.Drawing.Size(1, 150)
    ColumnHeadersVisible = $True
    DataSource = $tableData
}

$Form.Controls.Add($dataGridView)  
$Form.ShowDialog()
  • Related