DataGridView Length Returned

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 10 years and 10 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
Lery154
Posts: 48
Last visit: Fri Feb 20, 2015 12:36 pm

DataGridView Length Returned

Post by Lery154 »

I'm doing the following:

New > New Form > Grid Template

PowerShell Script as follows:
PowerShell Code
Double-click the code block to select all.
function OnApplicationLoad {
	#Note: This function is not called in Projects
	#Note: This function runs before the form is created
	#Note: To get the script directory in the Packager use: Split-Path $hostinvocation.MyCommand.path
	#Note: To get the console output in the Packager (Windows Mode) use: $ConsoleOutput (Type: System.Collections.ArrayList)
	#Important: Form controls cannot be accessed in this function
	#TODO: Add snapins and custom code to validate the application load
	
	return $true #return true for success or false for failure
}


function OnApplicationExit {
	#Note: This function is not called in Projects
	#Note: This function runs after the form is closed
	#TODO: Add custom code to clean up and unload snapins when the application exits
	
	$script:ExitCode = 0 #Set the exit code for the Packager
}

#region Control Helper Functions
function Load-DataGridView
{
	<#
	.SYNOPSIS
		This functions helps you load items into a DataGridView.

	.DESCRIPTION
		Use this function to dynamically load items into the DataGridView control.

	.PARAMETER  DataGridView
		The ComboBox control you want to add items to.

	.PARAMETER  Item
		The object or objects you wish to load into the ComboBox's items collection.
	
	.PARAMETER  DataMember
		Sets the name of the list or table in the data source for which the DataGridView is displaying data.

	#>
	Param (
		[ValidateNotNull()]
		[Parameter(Mandatory=$true)]
		[System.Windows.Forms.DataGridView]$DataGridView,
		[ValidateNotNull()]
		[Parameter(Mandatory=$true)]
		$Item,
	    [Parameter(Mandatory=$false)]
		[string]$DataMember
	)
	$DataGridView.SuspendLayout()
	$DataGridView.DataMember = $DataMember
	
	if ($Item -is [System.ComponentModel.IListSource]`
	-or $Item -is [System.ComponentModel.IBindingList] -or $Item -is [System.ComponentModel.IBindingListView] )
	{
		$DataGridView.DataSource = $Item
	}
	else
	{
		$array = New-Object System.Collections.ArrayList
		
		if ($Item -is [System.Collections.IList])
		{
			$array.AddRange($Item)
		}
		else
		{	
			$array.Add($Item)	
		}
		$DataGridView.DataSource = $array
	}
	
	$DataGridView.ResumeLayout()
}

function Convert-ToDataTable
{
	<#
		.SYNOPSIS
			Converts objects into a DataTable.
	
		.DESCRIPTION
			Converts objects into a DataTable, which are used for DataBinding.
	
		.PARAMETER  InputObject
			The input to convert into a DataTable.
	
		.PARAMETER  Table
			The DataTable you wish to load the input into.
	
		.PARAMETER RetainColumns
			This switch tells the function to keep the DataTable's existing columns.
		
		.PARAMETER FilterWMIProperties
			This switch removes WMI properties that start with an underline.
	
		.EXAMPLE
			Convert-ToDataTable -InputObject (Get-Process) -Table $DataTable
	#>
	
	param(
	$InputObject, 
	[ValidateNotNull()]
	[System.Data.DataTable]$Table,
	[switch]$RetainColumns,
	[switch]$FilterWMIProperties)
	
	if($InputObject -is [System.Data.DataTable])
	{
		$Table = $InputObject
		return
	}
	
	if(-not $RetainColumns -or $Table.Columns.Count -eq 0)
	{
		#Clear out the Table Contents
		$Table.Clear()

		if($InputObject -eq $null){ return } #Empty Data
		
		$object = $null
		#find the first non null value
		foreach($item in $InputObject)
		{
			if($item -ne $null)
			{
				$object = $item
				break	
			}
		}

		if($object -eq $null) { return } #All null then empty
		
		#Get all the properties in order to create the columns
		$properties = Get-Member -MemberType 'Properties' -InputObject $object
		foreach ($prop in $properties)
		{
			if(-not $FilterWMIProperties -or -not $prop.Name.StartsWith('__'))#filter out WMI properties
			{
				#Get the type from the Definition string
				$index = $prop.Definition.IndexOf(' ')
				$type = $null
				if($index -ne -1)
				{
					$typeName = $prop.Definition.SubString(0, $index)
					try{ $type = [System.Type]::GetType($typeName) } catch {}
				}

				if($type -ne $null -and [System.Type]::GetTypeCode($type) -ne 'Object')
				{
	      			[void]$table.Columns.Add($prop.Name, $type) 
				}
				else #Type info not found
				{ 
					[void]$table.Columns.Add($prop.Name) 	
				}
			}
	    }
	}
	else
	{
		$Table.Rows.Clear()	
	}
	
	$count = $table.Columns.Count
	foreach($item in $InputObject)
	{
		$row = $table.NewRow()
		
		for ($i = 0; $i -lt $count;$i++)
    	{
			$column = $table.Columns[$i]
			$prop = $column.ColumnName	
			
			$value = Invoke-Expression ('$item.{0}' -f $prop)
			if($value -ne $null)
			{
				$row[$i] = $value
			}
		}
		
		[void]$table.Rows.Add($row)
	}
}
#endregion

$FormEvent_Load={
	#TODO: Initialize Form Controls here
	
}

$buttonExit_Click={
	#TODO: Place custom script here
	$formMain.Close()
}

$buttonLoad_Click={
	#TODO: Place custom script here
#	---------------------------------
#	Sample Code to Load Grid
#	---------------------------------
#	$processes = Get-WmiObject Win32_Process -Namespace "Root\CIMV2"
#	Load-DataGridView -DataGridView $datagridviewResults -Item $processes
#	---------------------------------
#	Sample Code to Load Sortable Data
#	---------------------------------
# 	$processes = Get-WmiObject Win32_Process -Namespace "Root\CIMV2"
# 	$table = New-Object System.Data.DataTable
#	Convert-ToDataTable -InputObject $processes -Table $table -FilterWMIProperties
#	Load-DataGridView -DataGridView $datagridviewResults -Item $table
	$client = New-Object -ComObject Custom.Vendor
	$servername = $client.servername
	Load-DataGridView -DataGridView $datagridviewResults -Item $servername
}

$datagridviewResults_ColumnHeaderMouseClick=[System.Windows.Forms.DataGridViewCellMouseEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.DataGridViewCellMouseEventArgs]
	if($datagridviewResults.DataSource -is [System.Data.DataTable])
	{
		$column = $datagridviewResults.Columns[$_.ColumnIndex]
		$direction = [System.ComponentModel.ListSortDirection]::Ascending
		
		if($column.HeaderCell.SortGlyphDirection -eq 'Descending')
		{
			$direction = [System.ComponentModel.ListSortDirection]::Descending
		}

		$datagridviewResults.Sort($datagridviewResults.Columns[$_.ColumnIndex], $direction)
	}
}
You should notice the only PowerShell I'm adding is two lines:
PowerShell Code
Double-click the code block to select all.
$client = New-Object -ComObject Custom.Vendor
$servername = $client.servername
I'm then adding, as per the sample:
PowerShell Code
Double-click the code block to select all.
Load-DataGridView -DataGridView $datagridviewResults -Item $servername
When I run the form and click the Load button I get the following:
grid.png
grid.png (3.53 KiB) Viewed 6334 times
Why am I getting Length 25, instead of what should be the result of: machine123.domain.com

I get machine123.domain.com when I run:
PowerShell Code
Double-click the code block to select all.
$client = New-Object -ComObject Custom.Vendor
$servername = $client.servername
$servername
I will say when I change my powershell to a WMI query or different kind of query it works fine. So I'm not sure what is wrong?
User avatar
Lery154
Posts: 48
Last visit: Fri Feb 20, 2015 12:36 pm

Re: DataGridView Length Returned

Post by Lery154 »

So I think I resolved by own issue. I'm trying to get used to the differences in just running commands in PowerShell and creating GUI's. My commands that run in PowerShell need some changes when I put them into the GUI.
PowerShell Code
Double-click the code block to select all.
$client = New-Object -ComObject Custom.Vendor
$servername = $client.servername
Load-DataGridView -DataGridView $datagridviewResults $servername
If I do this, it works:
PowerShell Code
Double-click the code block to select all.
$button1_Click={
	#TODO: Place custom script here
	$services = New-Object -ComObject Custom.Vendor | Select-Object servername
	Load-DataGridView -DataGridView $datagridview1 $services
So it seems like this control expects the data to be formatted specifically. Lesson learned and I hope this information might help someone else.
This topic is 10 years and 10 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