Datagrid Row Selection

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 9 years and 9 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
User avatar
Ratoka
Posts: 8
Last visit: Wed Jan 03, 2018 9:18 am

Datagrid Row Selection

Post by Ratoka »

I am trying to extract a row object from a datagrid to pass back to another form but am running into some issues. It looks like the .SelectedRows is only returning the index of the selected row, and I am unsure of how to extract the rows data.

Here is the code to load the datagrid:
PowerShell Code
Double-click the code block to select all.
#Search for a matching user in AD
	#Variables
	$UserList = New-Object System.Collections.ArrayList
	
	#Search the listed OU bases
	$SearchOUs = @("OU=comp1,DC=contoso,DC=LOCAL", "OU=comp2,DC=contoso,DC=LOCAL")
	
	#Return the search
	ForEach ($OU in $SearchOUs)
	{
		$Search = $tbSearch.Text
		$Search = "*" + $Search + "*"
		$Users = Get-ADUser -Filter { cn -like $Search } -SearchBase $OU
		$UserList.AddRange([array]$Users)
	}
	
	#Add the search to the datagrid
	$dgUsers.DataSource = $UserList
}
I then on click of a button want to close the form, assign the selected row to a global variable which will then be loaded into a datagrid on a different form.
PowerShell Code
Double-click the code block to select all.
#Take the selected result from the datagrid and pass it back to main window
	$SelectedRow = $dgUsers.SelectedRows
	$Global:TermUsers = $SelectedRow
	$formAddTermUsers.Close()
Any help would be much appreciated, I am tearing my hair out on this.
User avatar
davidc
Posts: 5913
Last visit: Mon Jul 08, 2019 8:55 am
Been upvoted: 2 times

Re: Datagrid Row Selection

Post by davidc »

I don't recommend passing the DataRows since those may not exist after closing the form. Instead pass the objects from the Databinding. Each Row has a reference to the DataBound object:
PowerShell Code
Double-click the code block to select all.
$datagridviewResults.SelectedRows[0].DataBoundItem
David
David
SAPIEN Technologies, Inc.
This topic is 9 years and 9 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