Powershell - DataViewGrid - Column Autosize - powershell

I am a complete novice when it comes to .NET and powershell and was wondering if you guys could assist. I am generating a Data Grid from a .CSV on a form and would like the grid to auto size columns accordingly. Also if I could lock the columns/rows from user adjustment that would be amazing.
Clear-Host
Function Populate-CycleCountDataGrid {
$InventoryListArray = New-Object System.Collections.ArrayList
$Script:InventoryList = #(Import-CSV C:\File.csv | Write-Output)
$InventoryListArray.AddRange($Script:InventoryList)
$CycleCountDataGrid.DataSource = $InventoryListArray
}
Function GenerateForm {
$objForm = New-Object System.Windows.Forms.Form
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$RefreshButton_Click = {
Populate-CycleCountDataGrid
}
# Form Setup
#*******************************************************************************************\
$OnLoadForm_StateCorrection= { $objForm.WindowState = $InitialFormWindowState }
$objForm.Text = "CycleCount"
$objForm.Name = "CycleCount"
$objForm.Size = New-Object System.Drawing.Size(600,480)
$objForm.StartPosition = 0
$objForm.AutoSize = $False
$objForm.MinimizeBox = $False
$objForm.MaximizeBox = $False
$objForm.WindowState = "Normal"
# DataGrid
#*******************************************************************************************\
$CycleCountDataGrid = New-Object System.Windows.Forms.DataGrid
$CycleCountDataGrid.Location = New-Object System.Drawing.Size(0,0)
$CycleCountDataGrid.Size = New-Object System.Drawing.Size(592,400)
$CycleCountDataGrid.AutoSize = $False
$CycleCountDataGrid.AllowSorting = $False
$CycleCountDataGrid.ReadOnly = $True
$CycleCountDataGrid.CaptionText = "Inventory List"
$CycleCountDataGrid.HeaderFont = New-Object System.Drawing.Font("Verdana",8.25,1,3,0)
$CycleCountDataGrid.HeaderForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0)
$CycleCountDataGrid.Font = New-Object System.Drawing.Font("Verdana",8.25,[System.Drawing.FontStyle]::Bold)
$CycleCountDataGrid.BackColor = [System.Drawing.Color]::FromArgb(255,0,160,250)
$CycleCountDataGrid.AlternatingBackColor = [System.Drawing.Color]::FromArgb(255,133,194,255)
$CycleCountDataGrid.Name = "CycleCountDataGrid"
$CycleCountDataGrid.DataBindings.DefaultDataSourceUpdateMode = 0
$objForm.Controls.Add($CycleCountDataGrid)
#*******************************************************************************************/
# Refresh Button
#*******************************************************************************************\
$RefreshButton = New-Object System.Windows.Forms.Button
$RefreshButton.Location = New-Object System.Drawing.Size(0,400)
$RefreshButton.Size = New-Object System.Drawing.Size(590,45)
$RefreshButton.Name = "RefreshButton"
$RefreshButton.Text = "Refresh"
$RefreshButton.UseVisualStyleBackColor = $True
$RefreshButton.add_Click($RefreshButton_Click)
$RefreshButton.DataBindings.DefaultDataSourceUpdateMode = 0
$objForm.Controls.Add($RefreshButton)
#*******************************************************************************************/
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
$objForm.FormBorderStyle = 'Fixed3D'
$objForm.MaximizeBox = $False
$objForm.Add_FormClosing([System.Windows.Forms.FormClosingEventHandler]{
if ($objForm.DialogResult -eq "Cancel") {}
})
$InitialFormWindowState = $objForm.WindowState
$objForm.add_Load($OnLoadForm_StateCorrection)
$objForm.ShowDialog()
#*******************************************************************************************/
}
GenerateForm

Add the following code:
$CycleCountDataGrid.Columns | Foreach-Object{
$_.AutoSizeMode = [System.Windows.Forms.DataGridViewAutoSizeColumnMode]::AllCells
}

Change your control to a system.windows.forms.datagridview rather than just a datagrid. Then you have access to $CycleCountDataGrid.columns
Each column has a width property. The answer above will try to autosize each column but you could specify each one if you like.
$CycleCountDatarid.columns[0].width = 200
100 is the default

The secret to Autosizing a Windows.Forms.Datagrid is that it has a private method 'ColAutoResize' you can invoke with Reflection:
Function AutoResizeColumns([System.Windows.Forms.DataGrid] $dg1){
[System.Reflection.BindingFlags] $F = 'static','nonpublic','instance'
$ColAutoResizeMethod = $dg1.GetType().GetMethod('ColAutoResize', $F)
If($ColAutoResizeMethod) {
For ([int]$i = $dg1.FirstVisibleColumn; $i -lt $dg1.VisibleColumnCount; $i++){
$ColAutoResizeMethod.Invoke($dg1, $i) | Out-Null
}
}
}
Once you have that function, you can add it to the DataGrid's VisibleChanged and DataSourceChanged events so drawing and refreshing the DataGrid will invoke AutoResizeColumns:
$objForm.Controls["CycleCountDataGrid"].add_DatasourceChanged({ AutoResizeColumns $objForm.Controls["CycleCountDataGrid"] } )
$objForm.Controls["CycleCountDataGrid"].add_VisibleChanged({ AutoResizeColumns $objForm.Controls["CycleCountDataGrid"] } )
$objForm.ShowDialog() | Out-Null
There's probably a cleaner way to do this, but it's working for me.

Related

Populate ComboBox2 depending on ComboBox1 selection

Few days of searching and trying multiple options, but nothing is working actually. With the previous code posted.
I've imported all my objects from XAML (all set in variables), I don't know if that would be a problem for that. I don't think since everything else seems to work properly.
I just want my Tab2CBB2 to show values depending on the selection of Tab1CBB1. Anyone could help ? (I haven't paste the entire code, neither the paths but you can probably help me with that). Note that those are two of my multiple tries. Thanks
[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$xaml = #" ...
"#
#Read XAML (Parse it)
$reader=(New-Object System.Xml.XmlNodeReader $XAML)
$Window=[Windows.Markup.XamlReader]::Load( $reader )
$listQA14 = Get-ChildItem $pathQA14 -name
$listQA15 = Get-ChildItem $pathQA15 -name
$listDBQA = Get-ChildItem $pathDBQA -name
$Tab1CBB1_SelectedIndexChanged= {
$Tab1CBB2.Items.Clear() # Clear the list
$Tab1CBB2.Text = $null # Clear the current entry
Switch ($Tab1CBB1.Text) {
'QA14' {
$ListQA14 | ForEach { $Tab1CBB2.Items.Add($_) }
}
'QA15' {
$ListQA15 | ForEach { $Tab1CBB2.Items.Add($_) }
}
'ARIELDBQA' {
$ListDBQA | ForEach { $Tab1CBB2.Items.Add($_) }
}
}
}
$Tab1CBB1.add_SelectedIndexChanged($Tab1CBB1_SelectedIndexChanged)
#Displays the Window
$Window.ShowDialog() | out-null
Here is another option tried :
#ComboBox1------
$ItemsCBB1 = #('ARIELDBQA','QA14','QA15')
foreach ($Item in $ItemsCBB1) {
$Tab1CBB1.Items.Add($Item)
}
#ComboBox2-------
if ($Tab1CBB1.SelectedItem -eq 'QA14') {
$Tab1CBB2.Items.Clear()
foreach ($Serie in $listQA14) {
$Tab1CBB2.Items.Add($Serie)
}
}
elseif ($Tab1CBB1.SelectedItem -eq 'QA15') {
$Tab1CBB2.Items.Clear()
foreach ($Serie in $listQA15) {
$Tab1CBB2.Items.Add($Serie)
}
}
elseif ($Tab1CBB1.SelectedItem -eq 'listDBQA') {
$Tab1CBB2.Items.Clear()
foreach ($Serie in $listDBQA) {
$Tab1CBB2.Items.Add($Serie)
}
}
Tried this also : $Selection = $Tab1CBB1.SelectedItem.ToString()
Variable $selection put after 'if', but not working
Note that when I indicate what the current selection would be, it is working properly. The problem seems to come from 'recording' the selection a the time of clicking... Thnaks !
Basically, all you have to do is inside the $Tab1CBB1_SelectedIndexChanged scriptblock use the various lists with script scoping.
Without that, the variables are unknown inside the script block.
$Tab1CBB1_SelectedIndexChanged = {
$Tab1CBB2.Items.Clear() # Clear the list
$Tab1CBB2.Text = $null # Clear the current entry
switch ($Tab1CBB1.Text) {
'QA14' { $script:ListQA14 | ForEach-Object { $Tab1CBB2.Items.Add($_) } }
'QA15' { $script:ListQA15 | ForEach-Object { $Tab1CBB2.Items.Add($_) } }
'ARIELDBQA' { $script:ListDBQA | ForEach-Object { $Tab1CBB2.Items.Add($_) } }
}
}
Another method could be to dynamically get the items to enter in the combobox, especially since these are file lists and can change while your form is being used:
$Tab1CBB1_SelectedIndexChanged = {
$Tab1CBB2.Items.Clear() # Clear the list
$Tab1CBB2.Text = $null # Clear the current entry
switch ($Tab1CBB1.Text) {
'QA14' { $path = $script:pathQA14 ; break }
'QA15' { $path = $script:pathQA15 ; break }
'ARIELDBQA' { $path = $script:pathDBQA }
}
Get-ChildItem -Path $path -Name | ForEach-Object { $Tab1CBB2.Items.Add($_) }
}
A simple example of what you seem to be after is something like this.
### Powershell populate ComboBox 2 based on ComboBox 1 Selection
Add-type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$labelDoubleClickOnAnyItem = New-Object 'System.Windows.Forms.Label'
$listbox2 = New-Object 'System.Windows.Forms.ListBox'
$listbox1 = New-Object 'System.Windows.Forms.ListBox'
$buttonOK = New-Object 'System.Windows.Forms.Button'
$form1_Load={
$items=1..9 |
ForEach-Object {"List item $_"}
$listbox1.Items.AddRange($items)
}
$listbox1_MouseDoubleClick=[System.Windows.Forms.MouseEventHandler]{
$listbox2.Items.Add($listbox1.SelectedItem)
$listbox1.Items.Remove($listbox1.SelectedItem)
}
$listbox2_MouseDoubleClick=[System.Windows.Forms.MouseEventHandler]{
$listbox1.Items.Add($listbox2.SelectedItem)
$listbox2.Items.Remove($listbox2.SelectedItem)
}
$form1.Controls.Add($labelDoubleClickOnAnyItem)
$form1.Controls.Add($listbox2)
$form1.Controls.Add($listbox1)
$form1.Controls.Add($buttonOK)
$form1.AcceptButton = $buttonOK
$form1.ClientSize = '378, 388'
$form1.FormBorderStyle = 'FixedDialog'
$form1.MaximizeBox = $False
$form1.MinimizeBox = $False
$form1.Name = 'form1'
$form1.StartPosition = 'CenterScreen'
$form1.Text = 'Form'
$form1.add_Load($form1_Load)
$labelDoubleClickOnAnyItem.Font = 'Microsoft Sans Serif, 9.75pt, style=Bold, Italic'
$labelDoubleClickOnAnyItem.Location = '13, 13'
$labelDoubleClickOnAnyItem.Name = 'labelDoubleClickOnAnyItem'
$labelDoubleClickOnAnyItem.Size = '353, 41'
$labelDoubleClickOnAnyItem.TabIndex = 3
$labelDoubleClickOnAnyItem.Text = 'Double click on any item to move it from one box to the other.'
$listbox2.FormattingEnabled = $True
$listbox2.Location = '200, 67'
$listbox2.Name = 'listbox2'
$listbox2.Size = '166, 277'
$listbox2.Sorted = $True
$listbox2.TabIndex = 2
$listbox2.add_MouseDoubleClick($listbox2_MouseDoubleClick)
$listbox1.FormattingEnabled = $True
$listbox1.Location = '12, 67'
$listbox1.Name = 'listbox1'
$listbox1.Size = '167, 277'
$listbox1.Sorted = $True
$listbox1.TabIndex = 1
$listbox1.add_MouseDoubleClick($listbox1_MouseDoubleClick)
$buttonOK.Anchor = 'Bottom, Right'
$buttonOK.DialogResult = 'OK'
$buttonOK.Location = '291, 353'
$buttonOK.Name = 'buttonOK'
$buttonOK.Size = '75, 23'
$buttonOK.TabIndex = 0
$buttonOK.Text = '&OK'
$form1.ShowDialog()
Or even this using just the ComboBox elements
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.ClientSize = New-Object System.Drawing.Point(498,459)
$Form.text = 'Form'
$Form.TopMost = $false
$Form.StartPosition = 'CenterScreen'
$ComboBox1 = New-Object system.Windows.Forms.ComboBox
$ComboBox1.text = ''
$ComboBox1.width = 216
$ComboBox1.height = 75
#('ComboxItem1','ComboxItem2','ComboxItem3') |
ForEach-Object {[void] $ComboBox1.Items.Add($_)}
$ComboBox1.location = New-Object System.Drawing.Point(31,41)
$ComboBox1.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$ComboBox2 = New-Object system.Windows.Forms.ComboBox
$ComboBox2.text = ''
$ComboBox2.width = 213
$ComboBox2.height = 38
$ComboBox2.location = New-Object System.Drawing.Point(32,73)
$ComboBox2.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
Function Add-ItemToComboBox2
{
$ComboBox2.Items.Add($ComboBox1.SelectedItem)
$ComboBox2.Refresh()
}
$Form.controls.AddRange(
#(
$ComboBox1,
$ComboBox2
)
)
$ComboBox1.Add_SelectedIndexChanged({ Add-ItemToComboBox2 })
[void]$Form.ShowDialog()
You have not stated what UX/UI tool you are using to design and implement your
GUI. Yet, hard coding is also just a challenge. So consider using one of these for your UX/UI effort. Your UX/UI should just work, whether you have PowerShell code behind it (or any other language). Your PowerShell code should just work, regardless of the UX/UI that may be implemented. Your UX/UI code should be separate from your ops code. You call your ops code from the UX/UI.
Free:
https://poshgui.com
https://www.youtube.com/results?search_query=poshgui
https://visualstudio.microsoft.com/vs/community
Be sure to thoroughly read the licensing agreement for VS.
https://www.youtube.com/results?search_query=vs+2019+community+winforms
Purchase
https://ironmansoftware.com/psscriptpad
https://www.youtube.com/results?search_query=psscriptpad
https://ironmansoftware.com/powershell-pro-tools
https://www.youtube.com/results?search_query=powershell-pro-tools
https://www.sapien.com/software/powershell_studio
https://www.youtube.com/results?search_query=Sapien%27s+powershell+studio++winforms
https://visualstudio.microsoft.com/vs
https://www.youtube.com/results?search_query=vs+2019+community+winforms

Powershell Update an already active form

So I'm trying to insert red dots into some kind of map, which I do with creating new pictureboxes after reading their coordinates out of an txt-file.
My goal now is to remove or create new boxes, while the form.ShowDialog() was already used.
I found a way of closing the whole form and running everything again, which kind of works but is very ugly in my opinion. Was wondering if there is another way of checking if new coordinates have been added to the txt-file or removed and if that is the case, creating or removing the corresponding boxes.
(I tried .Refresh but that seems to do nothing at all)
function MakeForm {
[void][reflection.assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.Application]::EnableVisualStyles();
$form = new-object Windows.Forms.Form
$form.Text = "Image Viewer"
$form.Width = 270;
$form.Height = 270;
$path = (Get-Item "Insert Path here")
$path2 = (Get-Item "Insert Path here")
$img = [System.Drawing.Image]::Fromfile($path);
$img2 = [System.Drawing.Image]::FromFile($path2);
$test = Get-Content -Path "Insert Path here"
$test
$pictureBoxes = New-Object 'System.Collections.Generic.List[Windows.Forms.PictureBox]'
$i=1
Foreach ($Line in $test){
if ($Line -like "*in 2*"){
$i++
$Split1= $Line.Split(" ")
$x=$Split1[5]
$y=$Split1[6]
$pictureBox = New-Object Windows.Forms.PictureBox
$pictureBox.Width = $img.Size.Width;
$pictureBox.Height = $img.Size.Height;
$pictureBox.Location = New-object System.Drawing.Size($x,$y)
$pictureBox.Image = $img;
$form.Controls.Add($pictureBox)
$pictureBoxes.Add($pictureBox)
Write-Host $pictureBoxes[$i]
$form.Add_Shown( { $form.Activate() } )
}
}
$pictureBox20 = New-Object Windows.Forms.PictureBox
$pictureBox20.Width = $img2.Size.Width;
$pictureBox20.Height = $img2.Size.Height;
$pictureBox20.Image = $img2;
$form.Controls.Add($pictureBox20)
$button1 = New-Object System.Windows.Forms.Button
$button1.Width=25
$button1.Height=223
$button1.Location = New-Object System.Drawing.Point(223,0)
$form.Controls.Add($button1)
$button1.Add_Click({
#Button for removing a box for testing purposes
$form.Controls.Remove($pictureBoxes[3])
})
$button2 = New-Object System.Windows.Forms.Button
$button2.Width=25
$button2.Height=223
$button2.Location = New-Object System.Drawing.Point(260,0)
$form.Controls.Add($button2)
$button2.Add_Click({
#This Button should refresh the whole form, if possible without doing everything again
$form.Close()
$form.Dispose()
MakeForm
})
$form.Add_Shown( { $form.Activate() } )
$form.ShowDialog()
}
MakeForm

Prevent Powershell GUI from closing

I want to prevent my Powershell Form from closing after a submit button is pressed. After the function "search_PC" there is no more code and the form closes. I want to still be able to write stuff in there after the function is finished. I have already tried the pause function and while($true) loops. I would be very happy about an answer.
Import-Module ActiveDirectory
# Assembly for GUI
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# Create Form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Size = New-Object System.Drawing.Size(400,500)
$objForm.Backcolor="white"
$objForm.StartPosition = "CenterScreen"
$objForm.Text = "Example Software"
$objForm.Icon="C:\Users\...\icon.ico"
# Label
$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(80,30)
$objLabel1.Size = New-Object System.Drawing.Size(60,20)
$objLabel1.Text = "UserID:"
$objForm.Controls.Add($objLabel1)
# Textbox
$objTextBox1 = New-Object System.Windows.Forms.TextBox
$objTextBox1.Location = New-Object System.Drawing.Size(160,28)
$objTextBox1.Size = New-Object System.Drawing.Size(100,20)
$objForm.Controls.Add($objTextBox1)
# Label
$objLabel2 = New-Object System.Windows.Forms.Label
$objLabel2.Location = New-Object System.Drawing.Size(80,72)
$objLabel2.Size = New-Object System.Drawing.Size(80,20)
$objLabel2.Text = "PC-Name:"
$objForm.Controls.Add($objLabel2)
# Textbox
$objTextBox2 = New-Object System.Windows.Forms.TextBox
$objTextBox2.Location = New-Object System.Drawing.Size(160,70)
$objTextBox2.Size = New-Object System.Drawing.Size(100,20)
$objForm.Controls.Add($objTextBox2)
# Button for closing
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(100,220)
$CancelButton.Size = New-Object System.Drawing.Size(163,25)
$CancelButton.Text = "Exit"
$CancelButton.Name = "Exit"
$CancelButton.DialogResult = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
# Checkbox
$objTypeCheckbox1 = New-Object System.Windows.Forms.Checkbox
$objTypeCheckbox1.Location = New-Object System.Drawing.Size(80,120)
$objTypeCheckbox1.Size = New-Object System.Drawing.Size(500,20)
$objTypeCheckbox1.Text = "Internal Session Support"
$objTypeCheckbox1.TabIndex = 1
$objTypeCheckbox1.Add_Click({$objTypeCheckbox2.Checked = $false})
$objForm.Controls.Add($objTypeCheckbox1)
# Checkbox
$objTypeCheckbox2 = New-Object System.Windows.Forms.Checkbox
$objTypeCheckbox2.Location = New-Object System.Drawing.Size(80,140)
$objTypeCheckbox2.Size = New-Object System.Drawing.Size(500,20)
$objTypeCheckbox2.Text = "Session Support Internal & external"
$objTypeCheckbox2.TabIndex = 2
$objTypeCheckbox2.Add_Click({$objTypeCheckbox1.Checked = $false})
$objForm.Controls.Add($objTypeCheckbox2)
# Button fo checking the User Input
$SubmitButton = New-Object System.Windows.Forms.Button
$SubmitButton.Location = New-Object System.Drawing.Size(100,190)
$SubmitButton.Size = New-Object System.Drawing.Size(163,25)
$SubmitButton.Text = "Submit"
$SubmitButton.Name = "Submit"
$SubmitButton.DialogResult = "OK"
$objForm.AcceptButton = $SubmitButton
$SubmitButton.Add_Click({
$User = $objTextBox1.Text
$PC = $objTextBox2.Text
# Check if all User Inputs are filled out
if ( !($User.trim()) -or !($PC.trim()) ) {
[void] [Windows.Forms.MessageBox]::Show("Please fill out every value!", "Error", [Windows.Forms.MessageBoxButtons]::ok, [Windows.Forms.MessageBoxIcon]::Warning)}
if($objTypeCheckbox1.checked -eq $true) {$Software = "Internal"}
elseif($objTypeCheckbox2.checked -eq $true) {$Software = "Internal&External"}
else {[void] [Windows.Forms.MessageBox]::Show("Please fill out every value!", "Error", [Windows.Forms.MessageBoxButtons]::ok, [Windows.Forms.MessageBoxIcon]::Warning)}
search_user
})
$objForm.Controls.Add($SubmitButton)
$statusBar1 = New-Object System.Windows.Forms.StatusBar
$objForm.controls.add($statusBar1)
function createFile
{
$Date = Get-Date -Format d.M.yyyy
$Time = (Get-Date).ToString(„HH:mm:ss“)
$Time2 = (Get-Date).ToString(„HH-mm-ss“)
$Date2 = Get-Date -Format yyyy-M-d;
$FileName = $Time2 + " " + $Date2
$wrapper = New-Object PSObject -Property #{ 1 = $Date; 2 = $Time; 3 = $User; 4 = $PC; 5 = $Software }
Export-Csv -InputObject $wrapper -Path C:\Users\...\$FileName.csv -NoTypeInformation
[void] [Windows.Forms.MessageBox]::Show("Successful!")
}
function search_user
{
if (#(Get-ADUser -Filter {SamAccountName -eq $User}).Count -eq 0) {
$objTextBox1.BackColor = "Red";
$statusBar1.Text = "Couldn't find user!"
$objForm.Dispose()
}
else{$objTextBox1.BackColor = "Green"
search_PC}
}
function search_PC
{
$Client = $PC
if (#(Get-ADComputer -Filter {DNSHostName -eq $Client}).Count -eq 0) {
$objTextBox2.BackColor = "Red";
$statusBar1.Text = "Couldn't find PC!"
$objForm.Dispose()
}
else{$objTextBox2.BackColor = "Green"
createFile}
}
$objForm.ShowDialog() #Showing Form and elements
Screenshot of the form:
This line is your problem:
$SubmitButton.DialogResult = "OK"
It should be:
$SubmitButton.DialogResult = [System.Windows.Forms.DialogResult]::None
Or just be removed.
DialogResult

Intermittent unexpected results when moving rows in a DataGridView

I have a basic script as per my code below. So the purpose of this is to be able to move records up and down, when pressing the up or down buttons. This works some of the time, but intermittently it will not move a record (but the selected row will still move). Please try out my code, and move the first record up and down a few times, I hope you will soon see what I mean.
Thank you
Adam
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Data")
# Main Form
$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(510,450)
$Form.Text = "Test"
$Form.TopMost = $false
$Form.MinimizeBox = $false
$Form.MaximizeBox = $false
$Form.StartPosition = "CenterScreen"
$Form.FormBorderStyle = "FixedToolWindow"
# Datasource
$dt = New-Object System.Data.DataTable
[void]$dt.Columns.Add("Name")
[void]$dt.Columns.Add("Step")
[void]$dt.Rows.Add("Jack","1")
[void]$dt.Rows.Add("Jayden","2")
[void]$dt.Rows.Add("Dylan","3")
[void]$dt.Rows.Add("Ben","4")
# Datagridview
$DataGrid = New-Object System.Windows.Forms.DataGridView
$DataGrid.Location = New-Object System.Drawing.Size(10,10)
$DataGrid.Size = New-Object System.Drawing.Size(300,200)
$DataGrid.AllowUserToAddRows = $false
$DataGrid.DataSource = $dt
$DataGrid.DataBindings.DefaultDataSourceUpdateMode = 'OnPropertyChanged'
$DataGrid.AutoResizeColumns()
$Form.Controls.Add($DataGrid)
# Up Button
$upButton = New-Object System.Windows.Forms.Button
$upButton.Location = New-Object System.Drawing.Size(320,20)
$upButton.Size = New-Object System.Drawing.Size(90,40)
$upButton.Text = “Up”
$upButton.Add_Click({
moveRow -1
})
$Form.Controls.Add($upButton)
# Down Button
$downButton = New-Object System.Windows.Forms.Button
$downButton.Location = New-Object System.Drawing.Size(320,70)
$downButton.Size = New-Object System.Drawing.Size(90,40)
$downButton.Text = “Down”
$downButton.Add_Click({
moveRow 1
})
$Form.Controls.Add($downButton)
# Function to move record in DataGridView
function moveRow ($direction){
if ($DataGrid.SelectedRows[0] -ne $null){
$currentRow = $DataGrid.SelectedRows[0].Index
# Don't move up if you are at the top
if (($currentRow -eq 0) -and ($direction -eq -1)){
return
}
# Don't move down if you are at the bottom
elseif (($currentRow -eq ($DataGrid.Rows.Count - 1)) -and ($direction -eq 1)){
return
}
else {
# Get Current and New Values
$currentValue = $DataGrid.Rows[$currentRow].Cells["Step"].Value
$newRow = $currentRow + $direction
$newValue = $DataGrid.Rows[$newRow].Cells["Step"].Value
# Swap Values
$DataGrid.Rows[$currentRow].Cells["Step"].Value = $newValue
$DataGrid.Rows[$newRow].Cells["Step"].Value = $currentValue
# Sort and refresh DataGridView
$DataGrid.ClearSelection()
$DataGrid.Rows[$newRow].Selected = $true;
$DataGrid.Sort($DataGrid.Columns["Step"], "Ascending")
}
}
}
# Show Form
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()

Powershell DataGridView - looping through rows in checkbox column to see if checked

I'm trying to create a powershell form that will get all processes into a datagridview (which works OK so far). I'm then adding an additional column infront of the datasource with each row as a checkbox.
I'd then like to press a button on my form which starts the Function called Do-Grid, and it is meant to go through and see which checkboxes in this first column have been checked.
And this is where I get stuck. I'm unable to figure out how to loop through each row/cell only in this column and see which checkbox has been ticked (or have the value of true).
Thank you.
Function GenerateForm {
[Void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$ButtonUpdateGrid = New-Object Windows.Forms.Button
$ButtonUpdateGrid.Location = New-Object Drawing.Point 7,15
$ButtonUpdateGrid.size = New-Object Drawing.Point 90,23
$ButtonUpdateGrid.Text = "&Get Packages"
$ButtonUpdateGrid.add_click({Get-info})
$Button1 = New-Object Windows.Forms.Button
$Button1.Location = New-Object Drawing.Point 200,15
$Button1.size = New-Object Drawing.Point 90,23
$Button1.Text = "columns"
$button1.add_Click($button1_OnClick)
$ButtonStartExport = New-Object Windows.Forms.Button
$ButtonStartExport.Location = New-Object Drawing.Point 100,15
$ButtonStartExport.size = New-Object Drawing.Point 90,23
$ButtonStartExport.Text = "rows"
$ButtonStartExport.add_click({Do-Grid})
$dataGridView1 = New-Object System.Windows.Forms.DataGridView
$dataGridView1.Location = New-Object Drawing.Point 7,40
$dataGridView1.size = New-Object Drawing.Point 1000,700
$dataGridView1.MultiSelect = $false
$dataGridView1.ColumnHeadersVisible = $true
$dataGridView1.RowHeadersVisible = $false
$form = New-Object Windows.Forms.Form
$form.text = "Package Exporter v0.1"
$form.Size = New-Object Drawing.Point 1024, 768
$form.topmost = 1
$form.Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
$form.Controls.Add($dataGridView1)
$form.controls.add($Button1)
$form.controls.add($ButtonStartExport)
$form.controls.add($ButtonUpdateGrid)
#$form.add_Load($OnLoadForm)
$form.ShowDialog()
}
Function Get-info{
If($datagridview1.columncount -gt 0){
$dataGridview1.DataSource = $null
$DataGridView1.Columns.RemoveAt(0)
}
$Column1 = New-Object System.Windows.Forms.DataGridViewCheckBoxColumn
$Column1.width = 30
$Column1.name = "Exp"
$DataGridView1.Columns.Add($Column1)
$array = New-Object System.Collections.ArrayList
$Script:procInfo = get-process | Select-Object name, company, description, product, id, vm, fileversion
$array.AddRange($procInfo)
$dataGridview1.DataSource = $array
$form.refresh()
}
Function Do-Grid{
#?????????????????????????????????? not really sure what to do here
for($i=0;$i -le $datagridview1.Rows.Count;$i++){
write-host $datagridview1.Rows[$i].value
}
}
Generate Form
Function Do-Grid{
for($i=0;$i -lt $datagridview1.RowCount;$i++){
if($datagridview1.Rows[$i].Cells['exp'].Value -eq $true)
{
write-host "cell #$i is checked"
#uncheck it
#$datagridview1.Rows[$i].Cells['exp'].Value=$false
}
else
{
#check it
#$datagridview1.Rows[$i].Cells['exp'].Value=$true
write-host "cell #$i is not-checked"
}
}
}