Hi - I have an Export CSV button which exports the contents of the Datagridview to CSV using the code below.
It exports the data but in reverse order - the top row of my datagridview is the last row of my CSV file. Can anyone suggest a clean way to maintain row order?
$datagridviewhosts.SelectAll()
$datagridviewhosts.SelectedRows | Select-Object -expand DataBoundItem | Export-Csv -NoTypeInformation -Path "$SelectedPath\Hosts_$($CurrentDate).csv"
Many thanks
Exporting CSV from Datagridview reverses order
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.
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.
-
- Posts: 55
- Last visit: Thu Jun 24, 2021 3:05 am
-
- Posts: 55
- Last visit: Thu Jun 24, 2021 3:05 am
Re: Exporting CSV from Datagridview reverses order
Hi Jvierra
Thanks for getting back to me.
Yes, understood.
Let me put it another way - I put a list of hostnames in a textbox.
My query on the list of hostnames returns data to the datagridview in the same order as it is listed in the textbox.
All good so far.
I do not sort it once it is in there, I just wish to export it and keep the order.
However when I export-CSV it is being reverse ordered in the CSV file.
This is really frustrating for the users who use my tool and who predominantly work with the data in Excel.
They plug in host names, they wish to get results out to CSV in the same order they went in..
Many thanks for any advice
Thanks for getting back to me.
Yes, understood.
Let me put it another way - I put a list of hostnames in a textbox.
My query on the list of hostnames returns data to the datagridview in the same order as it is listed in the textbox.
All good so far.
I do not sort it once it is in there, I just wish to export it and keep the order.
However when I export-CSV it is being reverse ordered in the CSV file.
This is really frustrating for the users who use my tool and who predominantly work with the data in Excel.
They plug in host names, they wish to get results out to CSV in the same order they went in..
Many thanks for any advice
-
- Posts: 55
- Last visit: Thu Jun 24, 2021 3:05 am
Re: Exporting CSV from Datagridview reverses order
I was being stupid. I can just export the array that populated the Datagridview instead..
Re: Exporting CSV from Datagridview reverses order
The "SelectedRows" is in the order of last in first out. To get all rows in the order in the table do this:
Code: Select all
$datagridview1.Rows|
Select-Object -expand DataBoundItem |
Export-csv Results.csv -notype
-
- Posts: 55
- Last visit: Thu Jun 24, 2021 3:05 am