Stumped, trying to get data from datagridview on click

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Russtoleum
Posts: 9
Meble kuchenne na zamówienie - na wymiar - Wrocław
Joined: Wed Apr 22, 2020 11:07 am

Stumped, trying to get data from datagridview on click

Post by Russtoleum »

Product, version and build: Powershell Studio 2020 5.7.174
32 or 64 bit version of product: 64
Operating system: Win10
32 or 64 bit OS: 64

Hey everybody, so I'm scratching at the heels of an intermediate powershell competency, but I enjoy it. I was finally able to get PShell Studio and I'm coding an app just to learn my way around and I'm stuck. I simply won't abandon it, I have to know how to do this.
Anyway, my app polls the AD for stale users or computers and populates a data grid with info (I'm showing this for context and on the off chance someone would like to tell me how to make it better), like so:
  1. $buttonDG_Click={
  2.  
  3.     #TODO: Place custom script here
  4.  
  5.     $ResultsDGV01.Columns.Clear()
  6.  
  7.     #$ResultsDGV01.Rows.Clear()
  8.  
  9.     $ResultsDGV01.Refresh()
  10.  
  11.     $ResultsDGV01.AutoSizeColumnsMode = 'Fill'
  12.  
  13.     $filterDate = $datetimepicker1.Value.DateTime
  14.  
  15.     $buttonDG.Text = 'Processing...'
  16.  
  17.     $buttonDG.Enabled = $False
  18.  
  19.    
  20.  
  21.    
  22.  
  23.     If ($CommandCB.SelectedItem -eq 'AD Stale Users Report') {
  24.  
  25.         $UserListLLD = Get-ADUser -Filter * -SearchBase $domain -Properties CN, UserPrincipalName, lastLogonDate, whenCreated, logoncount, LogonWorkstations | ? {
  26.  
  27.             $_.lastLogonDate -le $filterdate
  28.  
  29.         } | Sort-Object CN
  30.  
  31.         $dt = New-Object System.Data.DataTable
  32.  
  33.         $dt.Columns.Add('User Name')
  34.  
  35.         $dt.Columns.Add('User Principal Name')
  36.  
  37.         $dt.Columns.Add('Last Logon Date')
  38.  
  39.         $dt.Columns.Add('When Created')
  40.  
  41.         $dt.Columns.Add('Logon Count')
  42.  
  43.         $dt.Columns.Add('Logon Workstations')
  44.  
  45.         $ResultsDGV01.DataSource = $dt
  46.  
  47.        
  48.  
  49.         $progressbar1.Maximum = $UserListLLD.count
  50.  
  51.         $progressbar1.Step = 1
  52.  
  53.         $progressbar1.Value = 0
  54.  
  55.         ForEach ($User In $UserListLLD) {
  56.  
  57.            
  58.  
  59.             $r = $dt.NewRow()
  60.  
  61.             $r['User Name'] = $User.cn
  62.  
  63.             $r['User Principal Name'] = $User.UserPrincipalName
  64.  
  65.             $r['Last Logon Date'] = $User.lastlogondate
  66.  
  67.             $r['When Created'] = $User.whencreated
  68.  
  69.             $r['Logon Count'] = $User.logoncount
  70.  
  71.             $r['Logon Workstations'] = $User.logonworkstations
  72.  
  73.            
  74.  
  75.             $dt.Rows.Add($r)
  76.  
  77.             $ResultsDGV01.DataSource = $dt
  78.  
  79.             $progressbar1.PerformStep()
  80.  
  81.             #Start-Sleep -Milliseconds .8
  82.  
  83.            
  84.  
  85.         }
  86.  
  87.         $labelResultsCount.Text = $($UserListLLD.Count)
  88.  
  89.        
  90.  
  91.     }
  92.  
  93.     ElseIf ($CommandCB.SelectedItem -eq 'AD Stale Computers Report') {
  94.  
  95.        
  96.  
  97.         $CompListLLD = Get-AdComputer -LDAPFilter "(name=*)" -SearchBase $domain -Properties Name, Lastlogondate | Where-Object {
  98.  
  99.             $_.lastlogondate -le $filterDate
  100.  
  101.         } | Sort-Object Name
  102.  
  103.        
  104.  
  105.         $dt = New-Object System.Data.DataTable
  106.  
  107.         $dt.Columns.Add('Computer Name')
  108.  
  109.         $dt.Columns.Add('Last Logon Date')
  110.  
  111.         $ResultsDGV01.DataSource = $dt
  112.  
  113.        
  114.  
  115.         $progressbar1.Maximum = $CompListLLD.count
  116.  
  117.         $progressbar1.Step = 1
  118.  
  119.         $progressbar1.Value = 0
  120.  
  121.        
  122.  
  123.         ForEach ($Comp In $CompListLLD) {
  124.  
  125.            
  126.  
  127.             $r = $dt.NewRow()
  128.  
  129.             $r['Computer Name'] = $Comp.Name
  130.  
  131.             $r['Last Logon Date'] = $Comp.lastlogondate
  132.  
  133.             $dt.Rows.Add($r)
  134.  
  135.             $ResultsDGV01.DataSource = $dt
  136.  
  137.             $progressbar1.PerformStep()
  138.  
  139.             #Start-Sleep -Milliseconds 5
  140.  
  141.         }
  142.  
  143.         $labelResultsCount.text = $($CompListLLD.Count)
  144.  
  145.         #$datagridview1.DataSource | export-csv c:\Users\aruss\documents\datagrid.csv -NoTypeInformation
  146.  
  147.     }
  148.  
  149.     elseif ($CommandCB.SelectedItem -eq 'Test') {
  150.  
  151.         $ResultsDGV01.DataSource = Get-AdComputer -LDAPFilter "(name=*)" -SearchBase $domain -Properties Name, Lastlogondate
  152.  
  153.     }
  154.  
  155.    
  156.  
  157.     $buttonDG.Enabled = $True
  158.  
  159.     $buttonDG.Text = "Show In DG"
  160.  
  161.    
  162.  
  163. }
That works great. So what I'm trying to add now is the ability to click one or multiple users and allow the end user to click a button to delete the user(s). It took me longer than I care to admit, you have to add the proper event via the Designer. After FINALLY figuring that out, and the correct event to use, I am still unable to send one or multiple row selections to an array for deletion. I found one example I can make work with my data, but I'm unable to translate into an action that sends the clicked rows to a variable. That is below.
  1. $ResultsDGV01_Click={
  2.  
  3.     #TODO: Place custom script here
  4.  
  5.     [void][System.Windows.Forms.MessageBox]::Show($ResultsDGV01.SelectedCells[0].FormattedValue,)
  6.  
  7. }
This works but like I said it won't translate to what I want. Sending the data to a variable.

I have tried the following as well:
  1. $Script:Test = $ResultsDGV01.CurrentRow.Cells["cn"].Value.ToString()
  2.  
  3.  
  4.  
  5. _________________________________________________________________________
  6.  
  7.  
  8.  
  9. $TBDeletedUser = $datagridview1.SelectedRows.Cells[3].Value
  10.  
  11.  
  12.  
  13. ___________________________________________________________________________
  14.  
  15.  
  16.  
  17. $TBDeletedUser = $datagridview1.Rows[$_.RowIndex].Cells[0].value
  18.  
  19.  
As well as a few others but I think you guys get the idea, I just wanted to exemplify that I have scoured the internet to figure this out (because I don't have the core knowledge and still struggle with the terminology so manuals without very similar examples to what I'm trying to do are difficult for me to interpret), so I'm finally posting here and hope someone can help. I appreciate any attempt to do so.

Thank you for your time.

User avatar
Alexander Riedel
Posts: 7344
Joined: Tue May 29, 2007 4:43 pm

Re: Stumped, trying to get data from datagridview on click

Post by Alexander Riedel »

[Topic moved by moderator]
Alexander Riedel
SAPIEN Technologies, Inc.

jvierra
Posts: 14368
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: Stumped, trying to get data from datagridview on click

Post by jvierra »

Can you please attach your PSF file. The code posted is not formatted well and very hard to read. For large amounts of code, posting as a file is best.

jvierra
Posts: 14368
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: Stumped, trying to get data from datagridview on click

Post by jvierra »

I should also note the a multi-select grid can best be processed by using a context menu or just the delete key. When the rows are being deleted there is an event that fires that hands you each row so you can process the rows or cancel the operation.

This is how the grid is designed to work with code. Any other approach just leads to too much unnecessary code and less control of the operation.

Russtoleum
Posts: 9
Joined: Wed Apr 22, 2020 11:07 am

Re: Stumped, trying to get data from datagridview on click

Post by Russtoleum »

Here you go, thank you for taking a look. I will look into a context menu while you take a look. I appreciate it.
Attachments
Toolbox - Copy.psf
(44.77 KiB) Downloaded 8 times

jvierra
Posts: 14368
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: Stumped, trying to get data from datagridview on click

Post by jvierra »

Interesting approach to building this. Not the simplest but it appears that it will work.
It would take less code to just get the AD object and use "ConvertTo-DataTable" to create the tables. Clearing the grid is not necessary ans assigning a new table does the same thing.

The following will remove the rows from the grid.

Code: Select all

	$rowIndex = $ResultsDGV01.SelectedRows.RowIndex
    $rowIndex |
        ForEach-Object{
            $row = $ResultsDGV01.Rows[$_]
            $ResultsDGV01.Rows.Remove($row)
        }


Russtoleum
Posts: 9
Joined: Wed Apr 22, 2020 11:07 am

Re: Stumped, trying to get data from datagridview on click

Post by Russtoleum »

Ha, yea, I figured I was over doing it. I appreciate you letting me down easy.

So I have apparently not communicated well. What I'm trying to do is make it so you click a row or many rows,and it will pull the user name or computer names from the first cell and keep that in an array variable. So you can click a button and the button will run a power shell loop that will delete those users and computers from the active directory.
foreach ($User in $Users) {
Remove-ADUser -credential $currentuserscredentials -identity $arrayvariablepopulatedbyclickingthedatagrid

Having them instantly removed from the visible list would be a bonus, so thank you for that.

Does that make sense?

jvierra
Posts: 14368
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: Stumped, trying to get data from datagridview on click

Post by jvierra »

Unfortunately your understanding of what a form is and what a data grid is are a bit limited.
A grid has a property called "SelectedRows". That contains all rows selected.

Russtoleum
Posts: 9
Joined: Wed Apr 22, 2020 11:07 am

Re: Stumped, trying to get data from datagridview on click

Post by Russtoleum »

That is absolutely true and I probably should have posted this before but with all the functions I tried above and even with your function I get this on click:

Index operation failed; the array index evaluated to null.

Even when I populate the datagrid with the method you suggested.

jvierra
Posts: 14368
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: Stumped, trying to get data from datagridview on click

Post by jvierra »

No idea what you are talking about. Please try to ask only one question at a time. Stick to the same issue or we will just go in circles.

Locked