Skip to main content

Enhancing Sapien PowerShell Studio’s Data Grid View Control

Today I thought that I would share one of my personal helper functions.  One of the neat things about Sapien’s PowerShell Studio is that when you add a control, you also get some neat functions added to your code to help you populate and use the control.  For example, when you add a DataGridView, Load-DataGridView and ConvertTo-DataGridView is added to your code.  Load-DataGridView helps you load a grid view.  ConvertTo-DataGridView helps you format the data.

I have my own ways of doing things at times and when what is provided does not do everything that I want, I code it myself.  Below is my code for Set-DGV.  I created this one to help me with word wrap and to control the order in which the columns appear. Take this code for example:

1

2

3

4

5

6

7

8

9

10

$Info = Get-NetAdapter | Select-Object -Property Name, DNSSuffix, IPAddresses,                                         SubnetMasks, Gateway, DNSServers, MACAddress, Status,                            

MediaType, MediaConnectionState, FullDuplex, LastErrorCode, Speed

      

Set-DGV -DGV $datagridview1 `

        -Data $Info `

        -ColumnOrder Name, Gateway, FullDuplex `

        -ColumnWidth 100, 100, 150, 200, 50, 50, 50 `

        -EnableWordWrap Name, MacAddress `

        -EnableRowAutoSize

First I save the objects that I want into the variable $Info.  I used Select-Object to remove the properties that I did not want to display.  When using the Set-DGV function, you need to tell which DataGridView control you want to populate with the –DVG parameter.  The –Data parameter contains the objects that you want to display.  If there are specific columns that you want listed first, place them in order with –ColumnOrder.  You can also specify the column width with the –ColumnWidth parameter.  The arguments are positional starting with the first column.  If you need word wrapping, use the –EnableWordWrap parameter.  Its arguments are the property names that need word wrapped enabled.  -EnableRowAutoSize will turn on row auto sizing for all rows.

This is close to the built in helper functions from Sapien, but it offers a few different features.  Here is some sample output.

image

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

 

<#

.SYNOPSIS

Allows for rapid creation of a DataGridViews content.

 

.PARAMETER DGV

This is the name of the DataGridView in your form that you want

to populate.

 

.PARAMETER Data

This is the object containing the information to be placed in the

DataGridView.

 

.PARAMETER ColumnOrder

The DataGridView will auto populate the columns.  You can specify, by column

name, the order that they should appear in. For Example, if you have an

object with the properties AA, BB, CC, and DD and you wanted to display them

in a different order, you would provide this parameter as follows:

 

-ColumnOrder DD, BB, AA, CC

 

.PARAMETER ColumnWidth

Determines the width, in pixels, for each column.  Provide a comma separated

list in integers for each column.  You do not need to provide a value for each

column.  The default width will be used.

 

.PARAMETER EnableWordWrap

Provide the column names of any column that you want to enable Word Wrap on.

 

.PARAMETER EnableRowAutoSize

This switch will allow the rows to dynamically grow in size to accommodate all

information in a the cell.

 

.EXAMPLE

$Script:Info = Get-NetAdapter | Select-Object -Property Name, DNSSuffix, IPAddresses,

SubnetMasks, Gateway, DNSServers, MACAddress, Status,

MediaType, MediaConnectionState, FullDuplex, LastErrorCode, Speed

 

Set-DGV -DGV $DGVTest1 `

             -Data $Script:Info `

                  -ColumnOrder Name, Gateway, FullDuplex `

                  -ColumnWidth 100, 100, 150, 200, 50, 50, 50 `

                  -EnableWordWrap Name, MacAddress `

                  -EnableRowAutoSize

 

Gathers information from the Get-NetAdapter cmdlet and then filters the object

to only the desired properties.  Next, send to the Set-DGV cmdlet.  The "Data"

parameter is the name of the Windows form control for the DataGridView. "ColumnOrder"

set the first 3 columns to "Name", "Gateway", "FullDuplex".  The remainder of the

columns will be in there default order.  The "ColumnWidth" parameter is setting

non-default width for the first 7 columns. "EnableWordWrap" is set on the two columns

for the properties "Name" and "MacAddress"  For Word wrap to work, the data needs

spaces in it.  This DGV is also allowed to resize the height of rows to fit the

content.

 

.NOTES

=============================================================================

Set-DGV

Version 1.0

Copyright 2014, All rights reserved.

-----------------------------------------------------------------------------

History:

Version 1.0

Parameters available:

- DGV

- Data

- ColumnOrder

- ColumnWidth

- EnableWordWrap

- EnableAutoSize

-----------------------------------------------------------------------------

Known Issues:

 

=============================================================================

#>

function Set-DGV

{

       Param (

              [Parameter(Mandatory = $true)]

              $DGV,

              [Parameter(Mandatory = $true)]

              $Data,

              [String[]]$ColumnOrder,

              [Int[]]

              $ColumnWidth,

              [String[]]$EnableWordWrap,

              [Switch]$EnableRowAutoSize

       )

       # Clear the DGV.  When the DGV refreshes, the data would otherwise

       # append causing repeat values.  This will prevent that.

       For ($X = 0; $X -lt $DGV.Rows.Count; $X++)

       {

              $DGV.Rows.RemoveAt($X)

              $DGV.Rows.Clear()

              $DGV.Columns.Clear()

       }

       # Create a ArrayList to hold the sorted column names.

       $ColumnNameList = New-Object System.Collections.ArrayList

       # Get a list of all the property names.

       $Names = $Data | Get-Member -MemberType Properties | Select-Object -ExpandProperty Name

       ForEach ($C in $Names)

       {

              $ColumnNameList.Add($C)

       }

       # Reorder the list if there is a preferred order for displaying the properties.

       For ($X = $ColumnOrder.count; $X -ge 0; $X--)

       {

              For ($Y = 0; $Y -lt $ColumnNameList.Count; $Y++)

              {

                     If ($ColumnOrder[$X] -eq $ColumnNameList[$Y])

                     {

                           # Standard swap algorythm.

                           $Temp = $ColumnNameList[$X]

                           $ColumnNameList[$X] = $ColumnOrder[$X]

                           $ColumnNameList[$Y] = $Temp

                     }

              }

       }

       # Display the column names in the DGV

       ForEach ($C in $ColumnNameList)

       {

              $ColumnCount = $DGV.ColumnCount + 1

              $DGV.ColumnCount = $ColumnCount

              $DGV.Columns[$ColumnCount - 1].HeaderText = "$C"

       }

       # Set the column widths

       # To ensure that the amount of information sent to this option does not exceed

       # the number of properties, the maximum number of columns that can have

       # their widths modified is set to the number of properties in the object being

       # display.  Then the number of column widths sent is evaluated.  The lesser of

       # the 2 is used to determine how many column widths to modify.

       If ($ColumnWidth -ne $null)

       {

              $MaxWidth = $ColumnNameList.Count

              If ($ColumnWidth.Count -lt $MaxWidth) { $MaxWidth = $ColumnWidth.count }

              For ($X = 0; $X -lt $MaxWidth; $X++)

              {

                     $DGV.Columns[$X].Width = $ColumnWidth[$X]

              }

       }

      

       # Enable word Wrap

       #$DGV.DefaultCellStyle.WrapMode = 'True'

       If ($EnableWordWrap -ne $null)

       {

              For ($X = 0; $X -lt $EnableWordWrap.Count; $X++)

              {

                     If ($EnableWordWrap[$X] -eq $ColumnNameList[$X])

                     {

                           $DGV.DefaultCellStyle.WrapMode = 'True'

                     }

              }

       }

       # Add the first row.

       $DGV.Rows.Add()

       # Get the number of rows to display

       $RowTotal = $Data.count

       # Set the current Row.

       $Row = 0

       # Work with one instance one at a time.

       foreach ($Item in $Data)

       {

              # Determine the Row Number

              For ($X = 0; $X -lt $ColumnNameList.Count; $X++)

              {

                     $DGV.Rows[$Row].Cells[$X].Value = $Item | Select-Object -ExpandProperty $ColumnNameList[$X]

                     # Allow for row auto resize.

                     If ($EnableRowAutoSize)

                     {

                           $DGV.AutoResizeRow($Row)

                     }

              }

              # Add the next row.

              If ($Row -lt $Data.Count - 1)

              {

                     $Row++

                     $DGV.Rows.Add()

              }

       }

} # End: Function Set-DGV

 

Comments

Anonymous said…
I've been battling with an intermittent DataGridView display problem and since using your code the problem has gone away. Thanks for posting this.
Unknown said…
hi, thank you very much for this post and function!
in the Studio you can configure cells as buttons, images and other properties.
when i use the function it overwrites these settings,
maybe you have some idea how to avoid this?
thank you again
Sean

Thank you for your suggestion. Most likely I will not be modifying this in the near future since it achieves the intended task for its creation. With that said, you are free to add functionality of you like.

Popular posts from this blog

How to list all the AD LDS instances on a server

AD LDS allows you to provide directory services to applications that are free of the confines of Active Directory.  To list all the AD LDS instances on a server, follow this procedure: Log into the server in question Open a command prompt. Type dsdbutil and press Enter Type List Instances and press Enter . You will receive a list of the instance name, both the LDAP and SSL port numbers, the location of the database, and its status.

How to run GPResult on a remote client with PowerShell

In the past, to run the GPResult command, you would need to either physically visit this client, have the user do it, or use and RDP connection.  In all cases, this will disrupt the user.  First, you need PowerShell remoting enabled on the target machine.  You can do this via Group Policy . Open PowerShell and type this command. Invoke-Command –ScriptBlock {GPResult /r} –ComputerName <ComputerName> Replace <ComputerName> with the name of the target.  Remember, the target needs to be online and accessible to you.

Error icon when creating a GPO Preference drive map

You may not have an error at all.  Take a look at the drive mapping below. The red triangle is what threw us off.  It is not an error.  It is simply a color representation of the Replace option of the Action field in the properties of the drive mappings. Create action This give you a green triangle. The Create action creates a new mapped drive for users. Replace Action The Replace action gives you a red triangle.  This action will delete and recreate mapped drives for users. The net result of the Replace action is to overwrite all existing settings associated with the mapped drive. If the drive mapping does not exist, then the Replace action creates a new drive mapping. Update Action The Update action will have a yellow triangle. Update will modify settings of an existing mapped drive for users. This action differs from Replace in that it only updates settings defined within the preference item. All other settings remain as configured on the ma...