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.
Locked
User avatar
Ratoka
Posts: 8
Joined: Wed Jun 04, 2014 10:36 am

Datagrid Row Selection

Post by Ratoka » Thu Jul 03, 2014 1:56 pm

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
Joined: Thu Aug 18, 2011 4:56 am

Re: Datagrid Row Selection

Post by davidc » Mon Jul 14, 2014 9:04 am

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.

Locked