We help IT Professionals succeed at work.
Get Started

VB.net DatagridView export to Fixed Length

triphen asked
Last Modified: 2015-04-21
Hello Experts,

I have a DataGridView that has been populated by SQL query. I want to export the data in the row in a fixed length format. (ie: 1 coloumn is 5 char, 2nd column is 7 chars, 3rd column is 2 chars, etc) Currently I have my code exporting to CSV, see below. I am lost on how to do fixed length....help?

        Try 'Export the results
            Dim filestartdate As String
            Dim fileenddate As String
            filestartdate = cal_StartDate.SelectionRange.Start.ToString("MM-dd-yyyy")
            fileenddate = cal_EndDate.SelectionRange.Start.ToString("MM-dd-yyyy")
            Dim exportpath As String
            Dim companyname As String
            Dim storenum As String
            companyname = dgv_SysInfo.Item(0, 0).Value.ToString
            storenum = dgv_SysInfo.Item(1, 0).Value.ToString
            exportpath = frm_Config.txt_ExportPath.Text
            Dim headers = (From header As DataGridViewColumn In dgv_Payroll.Columns.Cast(Of DataGridViewColumn)() _
          Select header.HeaderText).ToArray
            Dim rows = From row As DataGridViewRow In dgv_Payroll.Rows.Cast(Of DataGridViewRow)() _
                       Where Not row.IsNewRow _
                       Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
            Using sw As New IO.StreamWriter(exportpath & "\" & storenum & "-" & companyname & "-" & filestartdate & "   " & fileenddate & ".csv")
                sw.WriteLine(String.Join(",", headers))
                For Each r In rows
                    sw.WriteLine(String.Join(",", r))
            End Using
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MessageBox.Show(ex.Message, "Error: Exception", MessageBoxButtons.OK, MessageBoxIcon.Stop)
            Exit Sub
        End Try

Open in new window

Watch Question
Distinguished Expert 2017
This problem has been solved!
Unlock 2 Answers and 2 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE