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.
This topic is 3 years and 11 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
Russtoleum
Posts: 9
Last visit: Sat Nov 04, 2023 1:54 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.     #TODO: Place custom script here
  3.     $ResultsDGV01.Columns.Clear()
  4.     #$ResultsDGV01.Rows.Clear()
  5.     $ResultsDGV01.Refresh()
  6.     $ResultsDGV01.AutoSizeColumnsMode = 'Fill'
  7.     $filterDate = $datetimepicker1.Value.DateTime
  8.     $buttonDG.Text = 'Processing...'
  9.     $buttonDG.Enabled = $False
  10.    
  11.    
  12.     If ($CommandCB.SelectedItem -eq 'AD Stale Users Report') {
  13.         $UserListLLD = Get-ADUser -Filter * -SearchBase $domain -Properties CN, UserPrincipalName, lastLogonDate, whenCreated, logoncount, LogonWorkstations | ? {
  14.             $_.lastLogonDate -le $filterdate
  15.         } | Sort-Object CN
  16.         $dt = New-Object System.Data.DataTable
  17.         $dt.Columns.Add('User Name')
  18.         $dt.Columns.Add('User Principal Name')
  19.         $dt.Columns.Add('Last Logon Date')
  20.         $dt.Columns.Add('When Created')
  21.         $dt.Columns.Add('Logon Count')
  22.         $dt.Columns.Add('Logon Workstations')
  23.         $ResultsDGV01.DataSource = $dt
  24.        
  25.         $progressbar1.Maximum = $UserListLLD.count
  26.         $progressbar1.Step = 1
  27.         $progressbar1.Value = 0
  28.         ForEach ($User In $UserListLLD) {
  29.            
  30.             $r = $dt.NewRow()
  31.             $r['User Name'] = $User.cn
  32.             $r['User Principal Name'] = $User.UserPrincipalName
  33.             $r['Last Logon Date'] = $User.lastlogondate
  34.             $r['When Created'] = $User.whencreated
  35.             $r['Logon Count'] = $User.logoncount
  36.             $r['Logon Workstations'] = $User.logonworkstations
  37.            
  38.             $dt.Rows.Add($r)
  39.             $ResultsDGV01.DataSource = $dt
  40.             $progressbar1.PerformStep()
  41.             #Start-Sleep -Milliseconds .8
  42.            
  43.         }
  44.         $labelResultsCount.Text = $($UserListLLD.Count)
  45.        
  46.     }
  47.     ElseIf ($CommandCB.SelectedItem -eq 'AD Stale Computers Report') {
  48.        
  49.         $CompListLLD = Get-AdComputer -LDAPFilter "(name=*)" -SearchBase $domain -Properties Name, Lastlogondate | Where-Object {
  50.             $_.lastlogondate -le $filterDate
  51.         } | Sort-Object Name
  52.        
  53.         $dt = New-Object System.Data.DataTable
  54.         $dt.Columns.Add('Computer Name')
  55.         $dt.Columns.Add('Last Logon Date')
  56.         $ResultsDGV01.DataSource = $dt
  57.        
  58.         $progressbar1.Maximum = $CompListLLD.count
  59.         $progressbar1.Step = 1
  60.         $progressbar1.Value = 0
  61.        
  62.         ForEach ($Comp In $CompListLLD) {
  63.            
  64.             $r = $dt.NewRow()
  65.             $r['Computer Name'] = $Comp.Name
  66.             $r['Last Logon Date'] = $Comp.lastlogondate
  67.             $dt.Rows.Add($r)
  68.             $ResultsDGV01.DataSource = $dt
  69.             $progressbar1.PerformStep()
  70.             #Start-Sleep -Milliseconds 5
  71.         }
  72.         $labelResultsCount.text = $($CompListLLD.Count)
  73.         #$datagridview1.DataSource | export-csv c:\Users\aruss\documents\datagrid.csv -NoTypeInformation
  74.     }
  75.     elseif ($CommandCB.SelectedItem -eq 'Test') {
  76.         $ResultsDGV01.DataSource = Get-AdComputer -LDAPFilter "(name=*)" -SearchBase $domain -Properties Name, Lastlogondate
  77.     }
  78.    
  79.     $buttonDG.Enabled = $True
  80.     $buttonDG.Text = "Show In DG"
  81.    
  82. }
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.     #TODO: Place custom script here
  3.     [void][System.Windows.Forms.MessageBox]::Show($ResultsDGV01.SelectedCells[0].FormattedValue,)
  4. }
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. $TBDeletedUser = $datagridview1.SelectedRows.Cells[3].Value
  6.  
  7. ___________________________________________________________________________
  8.  
  9. $TBDeletedUser = $datagridview1.Rows[$_.RowIndex].Cells[0].value
  10.  
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: 8479
Last visit: Thu Mar 28, 2024 9:29 am
Answers: 20
Been upvoted: 37 times

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: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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
Last visit: Sat Nov 04, 2023 1:54 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 104 times
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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
Last visit: Sat Nov 04, 2023 1:54 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: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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
Last visit: Sat Nov 04, 2023 1:54 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: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

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.
This topic is 3 years and 11 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked