I am currently trying to update my datagridview via button click, add a user via text box and clicking a button i want the datagridview to update to reflect the current stat of the database.
I have the datagridview showing up on launch of the software, but when I click the add button and try to refresh it, the database does not show.
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
#JsonDb has $JsonDB.update and $JsonDB.Date
$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"
$AddClientNButton = new-object System.Windows.Forms.Button
$AddClientNButton.Location = new-object system.drawing.size(61,90)
$AddClientNButton.Size = new-object system.drawing.size(80,50)
$AddClientNButton.Text = "Add Client"
$AddClientNButton.Add_Click({AddClient})
$AddClientNButton.TabIndex = 10
$Form.Controls.Add($AddClientNButton)
$UserNametextBox = New-Object System.Windows.Forms.TextBox
$UserNametextBox.Location = New-Object System.Drawing.Point(1,1)
$UserNametextBox.Size = New-Object System.Drawing.Size(300,20)
$UserNametextBox.text="User Name"
$UserNametextBox.MaxLength = 6
$UserNametextBox.Add_Click({$this.SelectAll(); $this.Focus()})
$UserNametextBox.TabIndex = 0
$form.Controls.Add($UserNametextBox)
$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
AutoSizeColumnsMode = 'AllCells'
ColumnHeadersHeightSizeMode = 'AutoSize'
}
function AddClient
{
$jsonDB = Get-Content 'C:\Support\HardwareCollection.json' | Out-String | ConvertFrom-Json
$json.username
$Date = Get-Date -Format "MM/dd/yyyy HH:mm:ss K"
$Username = $UserNametextBox.text
if($jsonDB.username -eq $null)
{
$NewEntryItems=$Usernames
}
else
{
if($jsonDB.username -contains $Username)
{
$NewEntryItems =$null
}
else
{
$NewEntryItems = $username
}
}
$CollectionData = ForEach ($Username in $NewEntryItems)
{
New-Object PSObject -Property #{
Username = $Username
Date = $Date
}
}
$jsonDB += $CollectionData
$jsonDB | ConvertTo-Json -Compress |
Set-Content C:\Support\HardwareCollection.json
#refresh datagridview
$dataGridView.DataBindings.DefaultDataSourceUpdateMode = 0
$jsonDB = Get-Content 'C:\Support\HardwareCollection.json' | Out-String | ConvertFrom-Json
#$dataGridView.DataSource = $jsonDB
$tableData = New-Object System.Collections.ArrayList
$tableData.AddRange($jsonDB)
$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
AutoSizeColumnsMode = 'AllCells'
ColumnHeadersHeightSizeMode = 'AutoSize'
}
}
$Form.Controls.Add($dataGridView)
$Form.ShowDialog()
Any help would be amazing!!
I found the answer on another page. dumping this in fixed my issue.
$script:datagridview.DataBindings.DefaultDataSourceUpdateMode = 0
$script:datagridview.DataSource= $script:TableData
$script:datagridview.Refresh
Referenced Page
Related
I'm working on a little side project of listing outlook calendar meetings in the form data grid view.
I can populate columns with Subject and Start Date with no problem. For some reason, I can not populate a column with .DayOfWeekMask value, even though I can access this property via CLI. Any thoughts? Code below
add-type -AssemblyName 'System.Windows.Forms'
Add-Type -AssemblyName 'System.Drawing'
Add-Type -AssemblyName 'PresentationFramework'
$4 =
"BASE64 code"
$today = get-date
$Script:selection = #()
add-type -AssemblyName "Microsoft.Office.Interop.Outlook"
$outlookFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]
$outlook = New-Object -ComObject outlook.application
$namespace = $outlook.GetNamespace("MAPI")
$folder = $namespace.GetDefaultFolder($outlookFolders::olFolderCalendar)
$items = $folder.Items
$meetings = $items|?{$_.isRecurring -eq $true -and $_.Subject -notlike "*Canceled*" <#-and $_.GetRecurrencePattern().DayOfWeekMask -eq 18#>}|Select Subject, Start, #{l='Mask';e={$_.GetRecurrencePattern().DayOfWeekMask}}
$bitmap3 = New-Object System.Windows.Media.Imaging.BitmapImage
$bitmap3.BeginInit()
$bitmap3.StreamSource = [System.IO.MemoryStream][System.Convert]::FromBase64String($4)
$bitmap3.EndInit()
$bitmap3.Freeze()
$image3 = [System.Drawing.Bitmap][System.Drawing.Image]::FromStream($bitmap3.StreamSource)
$icon3 = [System.Drawing.Icon]::FromHandle($image3.GetHicon())
$main2 = New-Object System.Windows.Forms.Form
$main2.Icon = $icon3
$main2.ClientSize = '600,600'
$main2.MinimizeBox = $false
$main2.MaximizeBox = $false
$main2.Text = 'Options'
$main2.AutoSize = $true
$grid = New-Object System.Windows.Forms.DataGridView
$grid.Location = '5,5'
$grid.Height = 500
$grid.Width = 390
$grid.ColumnHeadersVisible = $true
$grid.AutoSizeColumnsMode = 'AllCells'
$grid.ColumnCount = 3
$grid.columns[0].Name = 'Name'
$grid.Columns[1].Name = 'Time'
$grid.Columns[2].Name = 'Day Mask'
$grid.MultiSelect = $true
$grid.SelectionMode = 'FullRowSelect'
$meetings|%{$grid.Rows.Add($($_.Subject), $($_.Start)), $($_.Mask)}
$button = [System.Windows.Forms.Button]::new()
$button.Location = [System.Drawing.Point]::new(5,540)
$button.Size = [System.Drawing.Size]::new(100,50)
$button.Text = 'OK'
$button.Add_Click({
$grid.SelectedRows|%{
$Script:selection += [pscustomobject]#{
Name = $grid.Rows[$_.Index].Cells[0].Value
Time = $grid.Rows[$_.Index].Cells[1].Value
}
}
})
$main2.Controls.AddRange(#($grid,$button))
$main2.ShowDialog()
update you datagrid wiht this one
$grid = New-Object System.Windows.Forms.DataGridView
$grid.Location = '5,5'
$grid.Height = 500
$grid.Width = 390
$grid.ColumnHeadersVisible = $true
$grid.AutoSizeColumnsMode = 'AllCells'
$grid.MultiSelect = $true
$grid.SelectionMode = 'FullRowSelect'
$array.AddRange($meetings)
$grid.DataSource=($array)
======= this datasourge work eveytime..
Based on the answer of #Kemal I removed .ColumnCount and subsequent Name properties. Created new ArrayList via $array = [System.Collections.ArrayList]::new() abd then applied Kemal's solution.
In th end the script looks like this.
add-type -AssemblyName 'System.Windows.Forms'
Add-Type -AssemblyName 'System.Drawing'
Add-Type -AssemblyName 'PresentationFramework'
$4 =
"BASE64 CODE"
$today = get-date
$selection =#()
$array = [System.Collections.ArrayList]::new()
add-type -AssemblyName "Microsoft.Office.Interop.Outlook"
$outlookFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]
$outlook = New-Object -ComObject outlook.application
$namespace = $outlook.GetNamespace("MAPI")
$folder = $namespace.GetDefaultFolder($outlookFolders::olFolderCalendar)
$items = $folder.Items
$meetings = $items|?{$_.isRecurring -eq $true -and $_.Subject -notlike "*Canceled*" |Select Subject, Start, #{l='Mask';e={$_.GetRecurrencePattern().DayOfWeekMask}}
$bitmap3 = New-Object System.Windows.Media.Imaging.BitmapImage
$bitmap3.BeginInit()
$bitmap3.StreamSource = [System.IO.MemoryStream][System.Convert]::FromBase64String($4)
$bitmap3.EndInit()
$bitmap3.Freeze()
$image3 = [System.Drawing.Bitmap][System.Drawing.Image]::FromStream($bitmap3.StreamSource)
$icon3 = [System.Drawing.Icon]::FromHandle($image3.GetHicon())
$main2 = New-Object System.Windows.Forms.Form
$main2.Icon = $icon3
$main2.ClientSize = '600,600'
$main2.MinimizeBox = $false
$main2.MaximizeBox = $false
$main2.Text = 'Options'
$main2.AutoSize = $true
$grid = New-Object System.Windows.Forms.DataGridView
$grid.Location = '5,5'
$grid.Height = 500
$grid.Width = 390
$grid.ColumnHeadersVisible = $true
$grid.AutoSizeColumnsMode = 'AllCells'
$grid.MultiSelect = $true
$grid.SelectionMode = 'FullRowSelect'
$array.AddRange($meetings)
$grid.DataSource=($array)
$button = [System.Windows.Forms.Button]::new()
$button.Location = [System.Drawing.Point]::new(5,540)
$button.Size = [System.Drawing.Size]::new(100,50)
$button.Text = 'OK'
$button.Add_Click({
$grid.SelectedRows|%{
$Script:selection += [pscustomobject]#{
Name = $grid.Rows[$_.Index].Cells[0].Value
Time = $grid.Rows[$_.Index].Cells[1].Value
DayofWeek = $grid.Rows[$_.Index].Cells[2].Value
}
}
})
$main2.Controls.AddRange(#($grid,$button))
$main2.ShowDialog()
I'm working on a script but for some reason my ProgressBar won't appear in my groupbox.
I tried a lot of different things (like making the groupbox trensparent) but nothing really work.
Here is my code 'simplified' with just the problematic parts.
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object System.Windows.Forms.Form
$Form.ClientSize = ‘345,160’
$Form.Text = " bug progressbar "
$Form.StartPosition = "CenterScreen"
#Functions
Function BDDchoice(){
$BDD = $args[0]
$Label2.Text = "it takes a few seconds"
$ProgressBarcheck = New-Object System.Windows.Forms.ProgressBar
$ProgressBarcheck.Location = New-Object System.Drawing.Point(230,49)
$ProgressBarcheck.Size = New-Object System.Drawing.Size(98, 23)
$ProgressBarcheck.Style = "Marquee"
$ProgressBarcheck.MarqueeAnimationSpeed = 20
$ButtonNEXT1.Hide()
$Form.Controls.Add($ProgressBarcheck);
$job1 ={
sleep 10
$bdd_min = $args[0]
echo $bdd_min
}
Start-Job -ScriptBlock $job1 -ArgumentList $BDD -Name bdd
do { [System.Windows.Forms.Application]::DoEvents() } until ((Get-Job -Name bdd).State -eq "Completed")
Wait-Job -Name bdd
$resultat = Receive-Job -Name bdd -Keep
Get-Job | Remove-Job -Force
$TextBoxBDD.text = $resultat
$ProgressBarcheck.Hide()
$ButtonNEXT1.Visible = $true
$Label2.Text = "BDD:"
}
#variables
$BDDXS = #('SCHEM1','SCHEM2','SCHEM3','SCHEM4')
$BDD1 = 'BDD1'
$BDD2 = 'BDD2'
$BDD3 = 'BDD3'
$BDD4 = 'BDD4'
$BDD = $null
#groupbox
$GroupBoxCREATE = New-Object System.Windows.Forms.GroupBox
$GroupBoxCREATE.Location = New-Object System.Drawing.Point(10,5)
$GroupBoxCREATE.Width = 325
$GroupBoxCREATE.Height = 150
$GroupBoxCREATE.Text = " Create "
#combobox ZONE
$comboBoxTRIG = New-Object System.Windows.Forms.ComboBox
$comboBoxTRIG.Location = New-Object System.Drawing.Point(25, 50)
$comboBoxTRIG.Size = New-Object System.Drawing.Size(200, 200)
foreach($BDDX in $BDDXS)
{
$comboBoxTRIG.Items.add($BDDX)
}
$comboBoxTRIG.Text = "REGION"
$comboBoxTRIG.AutoCompleteMode = "SuggestAppend"
$comboBoxTRIG.AutoCompleteSource = "ListItems"
$comboBoxTRIG.SelectedIndex ="0"
#butons
$ButtonNEXT1 = New-Object System.Windows.Forms.Button
$ButtonNEXT1.Location = New-Object System.Drawing.Point(230,49)
$ButtonNEXT1.Size = New-Object System.Drawing.Size(98, 23)
$ButtonNEXT1.Text = "OK"
$ButtonNEXT1.add_Click({
$zone = $comboBoxTRIG.SelectedItem.ToString()
if ($zone -like "SCHEM1"){
$BDD = $BDD1
}
if ($zone -like "SCHEM2") {
$BDD = $BDD2
}
if ($zone -like "SCHEM3") {
$BDD = $BDD3
}
if ($zone -like "SCHEM4") {
$BDD = $BDD4
}
BDDchoice($BDD)
})
#labels
$Label1 = New-Object System.Windows.Forms.Label
$Label1.Location = New-Object System.Drawing.Point(25,25)
$Label1.Text = "REGION :"
$Label2 = New-Object System.Windows.Forms.Label
$Label2.Location = New-Object System.Drawing.Point(25,80)
$label2.Width = 200
$Label2.Text = "BDD :"
#textbox
$TextBoxBDD = New-Object System.Windows.Forms.TextBox
$TextBoxBDD.Location = New-Object System.Drawing.Point(25,100)
$TextBoxBDD.Width = 200
$TextBoxBDD.ReadOnly = $true
$TextBoxBDD.Text = ""
$TextboxBDD.BackColor = "white"
#list form's butons/lists/combobox
$Form.Controls.AddRange(#($TextBoxBDD))
$Form.controls.AddRange(#($Label1,$Label2))
$Form.controls.AddRange(#($ButtonNEXT1))
$Form.controls.AddRange(#($comboBoxTRIG))
$Form.controls.AddRange(#($GroupBoxCREATE))
$Form.ShowDialog()
i'm interested in any idea.
My coworkers could not find anything but I must admit we are far from expert (i'm still learning and so are they).
$Form.Controls.Add($ProgressBarcheck);
It looks like you're adding Progress Bar to your form, NOT the groupbox. Add progress bar to groupbox then add groupbox to form.
$GroupBoxCREATE.Controls.Add($ProgressBarcheck);
$Form.Controls.Add($GroupBoxCREATE);
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
I need to create a checkbox automatically depends on folder I selected. I create ComboBox, then in the ComboBox, I can select which folder that I want to select. Inside of my folder, I have some file. The file consist of some extension file. I just need to pick 2 extension file from the folder, example(*.txt and *.csv).
After I select the folder, the checkBox will create automatically, the total of the checkBox depends on how many file exist in that folder with specific extension(*.txt and *.csv).
In my code, I already do some stuff, which is select the folder that I need to select, but still struggle with the checkBox. Anyone can help me please. Thank you so much. I really appreciate for the help.
I put my script in the ##2nd Updated.
Updated
Consider to #f6a4 answer, this is the result
The first picture is I just use this path to get the folder
'D:\Data\'
In the first picture, I already double click the folder1 and folder2, but the file do not appear.
The second picture, I specify the folder path
'D:\Data\folder1'
The second picture, the file appear because I specify the folder in the path, so the folder name do not appear in the please select folder box and return this error $CTRL_ListFolder.Items.AddRange( (Get-ChildItem -Path $GH.CurrentFold ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
2n Updated
I updated my script. But the file only appear 1, once I click the folder. And when I change to click other folder, It does not appear the file.
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Global:status = "inactive"
$Global:array = New-Object System.Collections.Generic.List[System.Object]
$Form = New-Object system.Windows.Forms.Form
$Form.text = "BPS Image Automation Utility"
$Form.BackColor = "#f6f6f6"
$Form.AutoSize = $true
$Form.FormBorderStyle = "FixedDialog"
$Form.MaximizeBox = $false
$Form.startposition = "centerscreen"
$Form.WindowState = 'Maximized'
$Label1 = New-Object system.Windows.Forms.Label
$Label1.text = "Please select the image"
$Label1.AutoSize = $true
$Label1.width = 25
$Label1.height = 10
$Label1.location = New-Object System.Drawing.Point(50,50)
$Label1.Font = 'Microsoft Sans Serif,10'
$Label1.ForeColor = "#000000"
$label1.AutoSize = $true
$Button3 = New-Object system.Windows.Forms.Button
$Button3.BackColor = "#136aa4"
$Button3.ForeColor = "#ffffff"
$Button3.text = "Done"
$Button3.width = 90
$Button3.height = 32
$Button3.AutoSize = $true
$Button3.UseCompatibleTextRendering = $True
$Button3.UseVisualStyleBackColor = $False
# $Button3.location = New-Object System.Drawing.Point(1700,920)
$Button3.Font = 'Microsoft Sans Serif,10'
# $Button3.Visible = $false
$Button2 = New-Object system.Windows.Forms.Button
$Button2.BackColor = "#136aa4"
$Button2.ForeColor = "#ffffff"
$Button2.text = "Delete"
$Button2.width = 90
$Button2.height = 32
$Button2.UseCompatibleTextRendering = $True
$Button2.UseVisualStyleBackColor = $False
$Button2.AutoSize = $true
# $Button2.location = New-Object System.Drawing.Point(1600,920)
$Button2.Font = 'Microsoft Sans Serif,10'
# $Button2.Visible = $false
$Panel = New-Object System.Windows.Forms.TableLayoutPanel
$panel.Dock = "Fill"
$panel.ColumnCount = 1
$panel.RowCount = 1
$panel.CellBorderStyle = "single"
$panel.ColumnStyles.Add((new-object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Percent, 100)))
$panel.RowStyles.Add((new-object System.Windows.Forms.RowStyle([System.Windows.Forms.SizeType]::Percent, 100)))
$Groupbox1 = New-Object system.Windows.Forms.Groupbox
$Groupbox1.text = "Job Handling"
$Groupbox1.Font = 'Microsoft Sans Serif,9'
$Groupbox1.AutoSize = $true
$Groupbox1.ForeColor = "#032d5d"
$Groupbox1.location = New-Object System.Drawing.Point(8,13)
$Groupbox1.Padding = New-Object -TypeName System.Windows.Forms.Padding -ArgumentList (0,5,5,0)
$Groupbox1.Dock = "fill"
$Groupbox1.UseCompatibleTextRendering = $True
$Groupbox2 = New-Object system.Windows.Forms.Groupbox
$Groupbox2.text = "Job Information"
$Groupbox2.Font = 'Microsoft Sans Serif,9'
$Groupbox2.AutoSize = $true
$Groupbox2.ForeColor = "#032d5d"
$Groupbox2.Dock = "None"
$Groupbox2.UseCompatibleTextRendering = $True
$ComboBox1 = New-Object system.Windows.Forms.ComboBox
$ComboBox1.BackColor = "#e8f3ff"
$ComboBox1.width = 190
$ComboBox1.height = 20
$ComboBox1.location = New-Object System.Drawing.Point(35,80)
$ComboBox1.Font = 'Microsoft Sans Serif,12'
$ComboBox1.AutoSize = $true
$ImageList = #(Get-ChildItem -Directory "D:\Process")
foreach ($img in $ImageList) {
$ComboBox1.Items.Add($img)
}
$ComboBox1.Add_Click({
if($ComboBox1.SelectedItem){
$Checkbox.Visible = $true
}
})
$Checkboxes += New-Object System.Windows.Forms.CheckBox
$Checkboxes = #()
$y = 20
$files = Get-ChildItem "D:\Process\$img" -Filter *.txt, *.csv
$files
foreach ($file in $files)
{
$Checkbox = New-Object System.Windows.Forms.CheckBox
$Checkbox.Text = $file
$Checkbox.Location = New-Object System.Drawing.Size(10,$y)
$Checkbox.Size = New-Object System.Drawing.Size(330,20)
$y += 30
$Groupbox2.Controls.Add($Checkbox)
$Checkboxes += $Checkbox
$Checkbox.Visible = $false
}
$Form.controls.AddRange(#($Panel))
$Panel.controls.AddRange(#($Groupbox1))
$Groupbox1.Controls.AddRange(#($Groupbox2, $ComboBox1, $Label1, $Button3, $Button2))
[void]$Form.Show()
$g2w = $Form.Width - 90
$g2h = $Form.Height - 270
$g2h
$Groupbox2.location = New-Object System.Drawing.Point(35,110)
$Groupbox2.size = New-Object System.Drawing.Size($g2w,$g2h)
$Groupbox2.AutoSize = $true
$bt2_w = $g2w - 55
$bt2_h = $g2h + 130
$Button2.location = New-Object System.Drawing.Point($bt2_w,$bt2_h)
$bt3_w = $g2w - 160
$Button3.location = New-Object System.Drawing.Point($bt3_w,$bt2_h)
$Form.Visible = $false
[void]$Form.ShowDialog()
This should do exactly what you want. By double click on a Directory you can browse through subdirectories as well.
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
# Global variables
$GH = [hashtable]::Synchronized(#{})
$GH.FolderPath = 'C:\Users\myUser\Desktop\csvfiles'
$GH.CurrentFolderPath = $GH.FolderPath
$GH.FileMask = #('*.txt','*.csv')
# windows form
$form = New-Object System.Windows.Forms.Form
$form.Visible = $false
[void]$form.SuspendLayout()
$form.Text = "File Selection"
$form.ClientSize = New-Object System.Drawing.Size(320,430)
$form.StartPosition = 'CenterScreen'
$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
# tab control
$CTRL_TabCtrl = New-Object System.Windows.Forms.TabControl
$CTRL_TabCtrl.Location = New-Object System.Drawing.Point(5,5)
$CTRL_TabCtrl.Size = New-Object System.Drawing.Size(310,420)
[void]$form.Controls.Add($CTRL_TabCtrl)
$CTRL_Tab1 = New-Object System.Windows.Forms.TabPage
$CTRL_Tab1.AutoSize = $true
$CTRL_Tab1.Text = 'Main'
$CTRL_Tab1.TabIndex = 1
[void]$CTRL_TabCtrl.Controls.Add($CTRL_Tab1)
# list folder
$CTRL_label10 = New-Object System.Windows.Forms.Label
$CTRL_label10.Location = New-Object System.Drawing.Point(10,10)
$CTRL_label10.Size = New-Object System.Drawing.Size(260,20)
$CTRL_label10.Name = 'Label10'
$CTRL_label10.Text = 'Please select a folder:'
[void]$CTRL_Tab1.Controls.Add($CTRL_label10)
$CTRL_ListFolder = New-Object System.Windows.Forms.Listbox
$CTRL_ListFolder.Location = New-Object System.Drawing.Point(10,30)
$CTRL_ListFolder.Size = New-Object System.Drawing.Size(280,60)
$CTRL_ListFolder.SelectionMode = [System.Windows.Forms.SelectionMode]::One
$CTRL_ListFolder.Items.AddRange( (Get-ChildItem -Path $GH.CurrentFolderPath -Directory).Name )
$CTRL_ListFolder.Enabled = $true
$CTRL_ListFolder.Add_MouseDoubleClick( {
$listFolder_innerevent = $true
if( $CTRL_ListFolder.SelectedItem -eq '..' ) {
$GH.CurrentFolderPath = $GH.CurrentFolderPath.Substring( 0, $GH.CurrentFolderPath.LastIndexOf( '\' ) )
[void]$CTRL_ListFolder.Items.Clear()
if( $GH.CurrentFolderPath.Length -gt $GH.FolderPath.Length ) {
[void]$CTRL_ListFolder.Items.Add( '..' )
}
$CTRL_ListFolder.Items.AddRange( (Get-ChildItem -Path $GH.CurrentFolderPath -Directory).Name )
[void]$CTRL_CheckListBox.Items.Clear()
$files = (Get-ChildItem -Path ($GH.CurrentFolderPath + '\*') -Include $GH.FileMask -File ).Name
if( $files ) {
[void]$CTRL_CheckListBox.Items.AddRange( $files )
}
}
else {
if( (Get-ChildItem -Path ($GH.CurrentFolderPath + '\' + $CTRL_ListFolder.SelectedItem) -Directory).Name ) {
$GH.CurrentFolderPath += '\' + $CTRL_ListFolder.SelectedItem
[void]$CTRL_ListFolder.Items.Clear()
[void]$CTRL_ListFolder.Items.Add( '..' )
[void]$CTRL_ListFolder.Items.AddRange( (Get-ChildItem -Path $GH.CurrentFolderPath -Directory).Name )
[void]$CTRL_CheckListBox.Items.Clear()
$files = (Get-ChildItem -Path ($GH.CurrentFolderPath + '\*') -Include $GH.FileMask -File ).Name
if( $files ) {
[void]$CTRL_CheckListBox.Items.AddRange( $files )
}
}
}
} )
[void]$CTRL_Tab1.Controls.Add($CTRL_ListFolder)
# list folder with check boxes for files
$CTRL_label12 = New-Object System.Windows.Forms.Label
$CTRL_label12.Location = New-Object System.Drawing.Point(10,100)
$CTRL_label12.Size = New-Object System.Drawing.Size(260,20)
$CTRL_label12.Name = 'Label12'
$CTRL_label12.Text = 'Files found:'
[void]$CTRL_Tab1.Controls.Add($CTRL_label12)
$CTRL_CheckListBox = New-Object System.Windows.Forms.CheckedListbox
$CTRL_CheckListBox.Location = New-Object System.Drawing.Point(10,120)
$CTRL_CheckListBox.Size = New-Object System.Drawing.Size(280,230)
$CTRL_CheckListBox.CheckOnClick = $true
$CTRL_CheckListBox.Enabled = $true
$files = (Get-ChildItem -Path ($GH.CurrentFolderPath + '\*') -Include $GH.FileMask -File ).Name
if( $files ) {
[void]$CTRL_CheckListBox.Items.AddRange( $files )
}
[void]$CTRL_Tab1.Controls.Add($CTRL_CheckListBox)
$CTRL_OKButton1 = New-Object System.Windows.Forms.Button
$CTRL_OKButton1.Location = New-Object System.Drawing.Point(70,365)
$CTRL_OKButton1.Size = New-Object System.Drawing.Size(75,23)
$CTRL_OKButton1.Text = 'OK'
$CTRL_OKButton1.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $CTRL_OKButton1
[void]$CTRL_Tab1.Controls.Add($CTRL_OKButton1)
$CTRL_CancelButton1 = New-Object System.Windows.Forms.Button
$CTRL_CancelButton1.Location = New-Object System.Drawing.Point(150,365)
$CTRL_CancelButton1.Size = New-Object System.Drawing.Size(75,23)
$CTRL_CancelButton1.Text = 'Cancel'
$CTRL_CancelButton1.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CTRL_CancelButton1
[void]$CTRL_Tab1.Controls.Add($CTRL_CancelButton1)
[void]$form.ResumeLayout()
$userInput = $form.ShowDialog()
if ($userInput -eq [System.Windows.Forms.DialogResult]::OK) {
# User clicked OK Button
}
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"
}
}
}