Saving DataGridView to .CSV using SaveFileDialog

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 5 years and 1 month 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
Ochness
Posts: 6
Last visit: Wed Oct 28, 2020 3:44 pm

Saving DataGridView to .CSV using SaveFileDialog

Post by Ochness »

I am trying to save the results of the DataGridView to a .CSV file using the SaveFileDialog command. I am able to name the file and it saves as a .CSV but when I open the CSV all of the data for a row is on one line.

here is the code I'm using:
  1.         $SaveChooser = New-Object -TypeName System.Windows.Forms.SaveFileDialog
  2.     $SaveChooser.Filter = "CSV file (*.csv)|*.csv| All Files (*.*)|*.*"
  3.     $SaveChooser.SupportMultiDottedExtensions = $true;
  4.    
  5.     if ($SaveChooser.ShowDialog() -eq 'OK')
  6.     {
  7.         $datagridview1.Rows | select -expand DataBoundItem | Out-File $SaveChooser.FileName
  8.     }
Any help or direction would be great. Thanks
User avatar
mxtrinidad
Posts: 399
Last visit: Tue May 16, 2023 6:52 am

Re: Saving DataGridView to .CSV using SaveFileDialog

Post by mxtrinidad »

The SaveFileDialog box doesn't transform PSObjects to a specifc file type.

You need to use the Export-Csv cmdlet so it can correctly convert the PSObject to a CSV file.
Ochness
Posts: 6
Last visit: Wed Oct 28, 2020 3:44 pm

Re: Saving DataGridView to .CSV using SaveFileDialog

Post by Ochness »

Thank you for your response.

I am new to PowerShell and forms so I'm not sure how I would use the SaveFileDialog and the Export-CSV together.

How would I use the Export-CSV in my current code?
User avatar
mxtrinidad
Posts: 399
Last visit: Tue May 16, 2023 6:52 am

Re: Saving DataGridView to .CSV using SaveFileDialog

Post by mxtrinidad »

Simple:
.. | Out-File $SaveChooser.FileName
to
.. | Export-Csv $SaveChooser.FileName -NoClobber -NoTypeInformation

Make sure to check the cmdlet help documentation:
Get-Help Export-Csv -detailed

:)
This topic is 5 years and 1 month 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