Only column text appears when csv file is imported to datagridview vb.net - vb.net

This is my first vb.net program, so please bear with me if my question is very mediocre.
Before mentioning my problem, the mechanism of my accounting program is that if the user would input data into the datagridview and export it, so that when he restarts the program, he can import the exported data.
I have imported this .csv file to my datagridview
The problem is that when I have imported it, only column texts would appear like this.
This is the export code that I have used to create the .csv file.
Private Sub ExportToExcelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExportToExcelToolStripMenuItem.Click
Dim msg1 = "Export Successful"
Dim title = "Excel Export"
MsgBox(msg1, , title)
Try
Dim iexport1 As String = ""
Dim eexport1 As String = ""
For Each C As DataGridViewColumn In Income.Columns
iexport1 &= """" & C.HeaderText & ""","
Next
iexport1 = iexport1.Substring(0, iexport1.Length - 1)
iexport1 &= Environment.NewLine
For Each R As DataGridViewRow In Income.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
iexport1 &= """" & C.Value.ToString & ""","
Else
iexport1 &= """" & "" & ""","
End If
Next
iexport1 = iexport1.Substring(0, iexport1.Length - 1)
iexport1 &= Environment.NewLine
Next
For Each C As DataGridViewColumn In Expense.Columns
eexport1 &= """" & C.HeaderText & ""","
Next
eexport1 = eexport1.Substring(0, eexport1.Length - 1)
eexport1 &= Environment.NewLine
For Each R As DataGridViewRow In Expense.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
eexport1 &= """" & C.Value.ToString & ""","
Else
eexport1 &= """" & "" & ""","
End If
Next
eexport1 = eexport1.Substring(0, eexport1.Length - 1)
eexport1 &= Environment.NewLine
Next
Dim tw As IO.TextWriter = New IO.StreamWriter(path:="C:\Users\S2009516\Desktop\JanuaryIncome.CSV")
tw.Write(iexport1)
tw.Close()
Dim tw2 As IO.TextWriter = New IO.StreamWriter(path:="C:\Users\S2009516\Desktop\JanuaryExpense.CSV")
tw2.Write(eexport1)
tw2.Close()
Catch ex As Exception
End Try
End Sub
And this is the one I have used for importing csv file.
Private Sub ImportFromExcelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ImportFromExcelToolStripMenuItem.Click
Dim expenseload1 As String = "C:\Users\S2009516\Desktop\JanuaryExpense.CSV"
Dim incomeload1 As String = "C:\Users\S2009516\Desktop\JanuaryIncome.CSV"
Try
Dim expensereader1 As New StreamReader(expenseload1, Encoding.Default)
Dim incomereader1 As New StreamReader(incomeload1, Encoding.Default)
Dim eline As String = ""
Dim iline As String = ""
Do
eline = expensereader1.ReadLine
iline = incomereader1.ReadLine
If eline Is Nothing Then Exit Do
If iline Is Nothing Then Exit Do
Dim words() As String = eline.Split(",")
Dim words2() As String = iline.Split(",")
Income.Rows.Add("")
Expense.Rows.Add("")
For ix As Integer = 0 To 3
Me.Income.Rows(Income.Rows.Count - 1).Cells(ix).Value = words2(ix)
Me.Expense.Rows(Income.Rows.Count - 1).Cells(ix).Value = words(ix)
Next
Loop
expensereader1.Close()
incomereader1.Close()
Catch ex As Exception
End Try
End Sub
I have no clue on why this is happening... I have followed all the steps in the tutorial video.. Please save my soul... I have been stuck with this for 2 days already.

Related

How to move DataGridView row to another DataGridView in another form, with CSV Datasource- VB.net

Im using a CSV to load data and save data from the DataGridView I have in a form. I would now like it so with a button click event I can send a row checked via the checkbox column on the DataGridView, to another dataGridView which is hosted in another form.
If it helps, here is the load im using to load and save the DataGridView contents.
Private Sub btnLoadDGVGeneral_Click(sender As Object, e As EventArgs) Handles btnLoadDGVGeneral.Click
' PURPOSE: Load CSV file containing tasks into DataGridView
' Clearing DGV Rows allows for Tasks to not double up when rebooting the program
dataGVGeneral.Rows.Clear()
'New Variable: fname, represents File Path of CSV as String
Dim fname As String = "E:\SAT\Work.io\Work.io\bin\Debug\ListofTasks.csv"
Dim reader As New StreamReader(fname, Encoding.Default)
Dim sline As String = ""
Dim colsexpected As Integer = 7
Dim r As Integer = 0
'StreamReader will the file Line by Line, and add it to the variable sline
'First sline statement is Out of Loop, as first line of CSV contains headings to what each figure represents in a line.
sline = reader.ReadLine
Do
'Now sline will read the 2nd line and so forth
sline = reader.ReadLine
'If no value is found on that line of the CSV file (at the end), then the loop will exit
If sline Is Nothing Then Exit Do
'Details is as a variable, which when called upon, places each value into different columns for that row
Dim details() As String = sline.Split(",")
dataGVGeneral.Rows.Add()
For i As Integer = 0 To 6
dataGVGeneral.Rows(r).Cells(i).Value = details(i)
Next
'Increments value of "r" by 1, meaning next line of CSV will be added to the next row.
Dim v As Integer = r + 1
r = v
Loop
reader.Close()
End Sub
Private Sub btnSaveGeneralDGV_Click(sender As Object, e As EventArgs) Handles btnSaveGeneralDGV.Click
Dim StrExport As String = ""
For Each C As DataGridViewColumn In dataGVGeneral.Columns
StrExport &= """" & C.HeaderText & ""","
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
For Each R As DataGridViewRow In dataGVGeneral.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
StrExport &= """" & C.Value.ToString & ""","
Else
StrExport &= """" & "" & ""","
End If
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
Next
Dim tw As System.IO.TextWriter = New System.IO.StreamWriter("E:\SAT\Work.io\Work.io\bin\Debug\ListofTasks.csv", False)
tw.Write(StrExport)
tw.Close()
End Sub

How can I export the datagridview to .csv without headers?

My csv file is like this
There is no blank spaces or whatsoever.
The problem as you can see is that I do not know how to export my datagridview as .csv excluding column headers.
This is how I have done my export code:
Private Sub IncomeToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles IncomeToolStripMenuItem.Click
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "CSV|*.csv"
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Dim incomefile As String = String.Empty
For Each column As DataGridViewColumn In Expense.Columns
incomefile = incomefile & column.HeaderText & ","
Next
incomefile = incomefile.TrimEnd(",")
incomefile = incomefile & vbCr & vbLf
For Each row As DataGridViewRow In Expense.Rows
For Each cell As DataGridViewCell In row.Cells
incomefile = incomefile & cell.FormattedValue.replace(",", "") & ","
Next
incomefile = incomefile.TrimEnd(",")
incomefile = incomefile & vbCr & vbLf
Next
System.IO.File.WriteAllText(saveFileDialog1.FileName, incomefile)
End If
Dim msg1 = "Export Successful"
Dim title = "Excel Export"
MsgBox(msg1, , title)
End Sub
Please advise me. Some others mentioned that I'd better off use datatable to export it, but since I started to learn computer programming 43 hours ago, I have no clue on how to declare the data i have put in my datagridview and export it as csv file.
Remove those lines
For Each column As DataGridViewColumn In Expense.Columns
incomefile = incomefile & column.HeaderText & ","
Next
Give this a try.
Private Sub BtnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnExport.Click
SFD.InitialDirectory = "C:\"
SFD.Title = "Save Your File"
SFD.Filter = "Microsoft Excel(*.xls)|*.xls|Comma Delimited File(*.csv)|*.Csv"
SFD.OverwritePrompt = True
SFD.ShowDialog()
strFileName = SFD.FileName
' If SFD.ShowDialog() = DialogResult.OK Then
If SFD.FilterIndex = 1 Then
Call export()
Else
Call csv()
End If
' End If
End Sub
Also, try it this way.
Dim numCols As DataGridViewCell
Dim sw As New System.IO.StreamWriter("d:\\output.txt")
For Each numRows As DataGridViewRow In DataGridView1.Rows
Dim intCellCount As Integer = numRows .Cells.Count
Dim intCounter As Integer = 1
For Each numCols In numRows .Cells()
If intCounter <> intCellCount Then
sw.Write(numCols .Value.ToString & ",")
Else
sw.WriteLine(numCols .Value.ToString)
End If
intCounter += 1
Next
Next

Code to show a DataGridView works only if I run another sub before

I wrote a code to show/hide content of a certain DataTable into a DataGridView.
DataGridView appears and disappears when I click a button.
I don't get errors but nothing is shown.
But if I click another button (who shows another form) and then go back to the main form, the code works. (??!!??)
I wasn't able to understand what (in the 2nd code) makes the first code to work: it seems there aren't connections between two codes.
EDIT
I made some tests and I can add more informations:
I added a button to show (in a msgbox) the DataGridView properties.
The control was correctly added and all properties are correct.
The property "Visible" is set "True" but the DataGridView is still "invisible".
I added a button that sets DGV_Tbl.Visible = False and DGV_Tbl.Visible = True
And when I click it the DataGridView appears.
But if I click Btn_ShowHideTbl again (to remove DGV) and again (to re-add DGV) DataGridView is still "invisible".
This doesn't happens when I click the button to open the second form and then I close it to go back to the first form.
In this case all works correctly.
I could solve adding DGV_Tbl.Visible = False and DGV_Tbl.Visible = True to the first code but I don't think it's a good idea.
I would like to understand the problem and solve it without "strange instructions".
EDIT 2
I noticed that also the code .AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells) doesn't work without opening the 2nd form.
On this istruction DGV_Tbl.Visible = False and DGV_Tbl.Visible = True haven't effect.
EDIT 3
I've done as in the accepted answer, but I posted another question here hoping to understand what's wrong in my code.
This is my code to show/hide DataGridView:
Private Sub Btn_ShowHideTbl_Click(sender As Object, e As EventArgs) Handles Btn_ShowHideTbl.Click
ShowHideTbl()
End Sub
Private Sub ShowHideTbl()
'Look for DGV
Dim DGV_Tbl As DataGridView = Nothing
Try
DGV_Tbl = CType(Me.Controls("DGV_Tbl"), DataGridView)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Try
'If not found I need to show data
If DGV_Tbl Is Nothing Then
If Me.CBox_ProcType.Text = "Select a Procedure" Then
MsgBox("You need To select a Procedure", vbInformation, "Unable to show table")
Exit Sub
End If
DGV_Tbl = New DataGridView
'It needs to copy data to another DataTable to show Double as Currency
Using DTemp As DataTable = New DataTable
Dim TblName As String = Me.CBox_ProcType.Text
For C As Integer = 0 To DS_All.Tables(TblName).Columns.Count - 1
DTemp.Columns.Add(DS_All.Tables(TblName).Columns(C).ColumnName, Type.GetType("System.String"))
Next
Dim Arr(DS_All.Tables(TblName).Columns.Count - 1) As String
For R As Integer = 0 To DS_All.Tables(TblName).Rows.Count - 1
For C As Integer = 0 To DS_All.Tables(TblName).Columns.Count - 1
If C = 0 Then
Arr(C) = DS_All.Tables(TblName).Rows(R)(C).ToString
Else
Arr(C) = FormatCurrency(DS_All.Tables(TblName).Rows(R)(C).ToString, 2)
End If
Next
DTemp.Rows.Add(Arr)
Next
'Working on created DataGridView
With DGV_Tbl
.Name = "DGV_Tbl"
'Add control to the Form
Me.Controls.Add(DGV_Tbl)
.DataSource = DTemp
.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
.RowHeadersVisible = False
.AllowUserToAddRows = False
.AllowUserToDeleteRows = False
End With
'Dispose the copied DataTable
End Using
'Resizing Form to include new DataGridView
Dim DGV_H As Integer = 0
Dim DGV_W As Integer = 0
For Each R As DataGridViewRow In DGV_Tbl.Rows
DGV_H += R.Height
Next
DGV_H += DGV_Tbl.ColumnHeadersHeight
'Add more space to include spaces between cells
DGV_H += CInt(DGV_Tbl.Rows.Count * 0.45)
For Each C As DataGridViewColumn In DGV_Tbl.Columns
DGV_W += C.Width
Next
'Add more space to include spaces between cells
DGV_W += CInt(DGV_Tbl.Columns.Count * 0.45)
DGV_Tbl.Height = DGV_H
DGV_Tbl.Width = DGV_W
'Resize the Form
Me.Height += DGV_H + 30
Me.Controls("DGV_Tbl").Location = New Point(15, Me.Height - DGV_H - 30)
'Align for currency
For x As Integer = 1 To DGV_Tbl.Columns.Count - 1
DGV_Tbl.Columns(x).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
Next
Else
'If DGV exists I need to remove it and resize the form
Dim DGV_H As Integer = DGV_Tbl.Height
DGV_Tbl.Dispose()
Me.Height -= (DGV_H + 30)
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
This is the code in the button who shows another form (and the code to close the form and go back):
Private Sub Btn_ShowSummary_Click(sender As Object, e As EventArgs) Handles Btn_ShowSummary.Click
Try
If Me.CBox_ProcType.Text = "Select a Procedure" OrElse Me.CBox_ProcValue.Text = "Select a Value" Then
MsgBox("It needs to select a Procedure and a Value",
vbInformation, "Unable to show table")
Exit Sub
End If
Summary = "...Here Some text..." & vbCrLf & Split(Me.CBox_ProcType.Text, ".")(1).Trim & vbCrLf & vbCrLf
Summary &= "...Here Some text..." & Me.CBox_ProcValue.Text & vbCrLf & vbCrLf
Dim C1Wdt% = -50
Dim C2Wdt% = TBox_TotAll.Text.Length
For R As Integer = 1 To 4
Dim CBox_Phase As CheckBox = CType(Me.TLP_Phases.Controls("CBox_Phase" & R.ToString), CheckBox)
Dim TBox_ValPh As TextBox = CType(Me.TLP_Phases.Controls("TBox_ValPh" & R.ToString), TextBox)
If CBox_Phase.Checked Then
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}",
CBox_Phase.Text, TBox_ValPh.Text) & vbCrLf
Dim TBox_SelVarPh As TextBox = CType(Me.TLP_Phases.Controls("TBox_SelVarPh" & R.ToString), TextBox)
If TBox_SelVarPh.Text = "" OrElse TBox_SelVarPh.Text = "€ 0,00" Then
Summary &= "...Here Some text..." & vbCrLf
Else
Dim SelVarTxt$ = If(Val(TBox_SelVarPh.Text) > 0,
"...Here Some text..." & TBox_SelVarPh.Text,
"...Here Some text..." & TBox_SelVarPh.Text.Substring(1)) & vbCrLf
Summary &= SelVarTxt
End If
End If
Next
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}", "", New String(CChar("_"), C2Wdt)) & vbCrLf
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}",
"...Here Some text...",
Me.TBox_TotPhases.Text) & vbCrLf
If Me.TBox_PrtAdg.Text <> "€ 0,00" Then
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}",
"...Here Some text...",
Me.TBox_PrtAdg.Text) & vbCrLf
Summary &= "...Here Some text..." & TBox_PrtRapp.Text & "...Here Some text..." & TBox_CPrt.Text & "...Here Some text..." & vbCrLf
End If
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}",
"...Here Some text..." & TBox_ForfPercent.Text,
Me.TBox_ForfImp.Text) & vbCrLf
Summary &= "...Here Some text..." & TBox_TotPhases.Text & ")" & vbCrLf
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}", "", New String(CChar("_"), C2Wdt)) & vbCrLf
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}",
"...Here Some text...",
Me.TBox_TotAll.Text) & vbCrLf
Me.Hide()
Me.ShowInTaskbar = False
Frm_Summary.Show()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Here the code of the back button:
Private Sub Btn_CloseNBack_Click(sender As Object, e As EventArgs) Handles Btn_CloseNBack.Click
Frm_Base.ShowInTaskbar = True
Frm_Base.Show()
Me.Close()
End Sub
I don't see any connetion between the codes (but it seems I'm wrong) please show me what I'm missing.
May I suggest another approach for your problem ?
If i were you, i would think about using a drawn datagridview, put datatable content into it before hand.
Then in the show/hide button, just switch the visibility of that datagridview along with recalculating the form size.
As for the currency column, instead of making another table, you can just populate the datatable into your datagridview, then set the format of that column into currency:
DGV_Tbl.Columns("CurrencyColumn").DefaultCellStyle.Format = "c"
More information about datagridview column formatting can be found here

Excel export without Interop

I'm trying to accomplish export to Excel from a VB.NET (Windows Forms) application.
Unfortunately, I can't use Office Interops because the application should work on every machine - even if there is no Excel installed.
I found the following sample on the Net:
Public Sub ExportDatasetToExcel(ByVal ds As DataSet, Optional ByVal strHeader As String = "Save As")
'Proudly copied from:
'http://www.daniweb.com/software-development/vbnet/threads/368400/write-into-excel-using-oledb-connection#post1583200
Dim fileSave As New SaveFileDialog()
fileSave.Filter = "Excel 97-2003 Workbook (*.xls)|*.xls"
fileSave.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
fileSave.Title = strHeader
fileSave.ShowDialog()
Dim xlsFilePath As String = fileSave.FileName
If xlsFilePath = "" Then
Exit Sub
End If
System.IO.File.Copy(storagePath & "\" & "empty.xls", xlsFilePath)
Cursor.Current = Cursors.WaitCursor
Dim conn As New OleDb.OleDbConnection(String.Format("provider=Microsoft.Jet.OLEDB.4.0; Data Source='{0}';" & "Extended Properties='Excel 8.0;HDR=YES;'", xlsFilePath))
conn.Open()
Dim strTableQ(ds.Tables.Count) As String
Dim i As Integer = 0
'making table query
For i = 0 To ds.Tables.Count - 1
strTableQ(i) = "CREATE TABLE [" & ds.Tables(i).TableName & "]("
Dim j As Integer = 0
For j = 0 To ds.Tables(i).Columns.Count - 1
Dim dCol As DataColumn
dCol = ds.Tables(i).Columns(j)
strTableQ(i) &= " [" & dCol.ColumnName & "] varchar(255) , "
Next
strTableQ(i) = strTableQ(i).Substring(0, strTableQ(i).Length - 2)
strTableQ(i) &= ")"
Dim cmd As New OleDb.OleDbCommand(strTableQ(i), conn)
cmd.ExecuteNonQuery()
Next
'making insert query
Dim strInsertQ(ds.Tables.Count - 1) As String
For i = 0 To ds.Tables.Count - 1
strInsertQ(i) = "Insert Into " & ds.Tables(i).TableName & " Values ("
For k As Integer = 0 To ds.Tables(i).Columns.Count - 1
strInsertQ(i) &= "#" & ds.Tables(i).Columns(k).ColumnName & " , "
Next
strInsertQ(i) = strInsertQ(i).Substring(0, strInsertQ(i).Length - 2)
strInsertQ(i) &= ")"
Next
'Now inserting data
For i = 0 To ds.Tables.Count - 1
For j As Integer = 0 To ds.Tables(i).Rows.Count - 1
Dim cmd As New OleDb.OleDbCommand(strInsertQ(i), conn)
For k As Integer = 0 To ds.Tables(i).Columns.Count - 1
cmd.Parameters.AddWithValue("#" & ds.Tables(i).Columns(k).ColumnName.ToString(), ds.Tables(i).Rows(j)(k).ToString())
Next
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
Next
Next
conn.Close()
conn.Dispose()
Cursor.Current = Cursors.Default
End Sub
This code works and exports my dataset to an .xls file.
The problem: I can't open this file while my program is running. It seems my program is still having a handle on this file. I can see it whenever I use the Sysinternals Process Explorer. If I close my program, I can open this file without any problems.
I think I have to destroy some object or just close the file. Please could anyone help a noob to accomplish it?
I don't know if this is the problem, it could. You do not Dispose the OleDbCommand objects. It's possible that it maintains a reference to the file. Try this:
Public Sub ExportDatasetToExcel(ByVal ds As DataSet, Optional ByVal strHeader As String = "Save As")
'Proudly copied from:
'http://www.daniweb.com/software-development/vbnet/threads/368400/write-into-excel-using-oledb-connection#post1583200
Using fileSave As New SaveFileDialog()
fileSave.Filter = "Excel 97-2003 Workbook (*.xls)|*.xls"
fileSave.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
fileSave.Title = strHeader
If fileSave.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim xlsFilePath As String = fileSave.FileName
If xlsFilePath = "" Then Exit Sub
System.IO.File.Copy(storagePath & "\" & "empty.xls", xlsFilePath)
Cursor.Current = Cursors.WaitCursor
Using conn As New OleDb.OleDbConnection(String.Format("provider=Microsoft.Jet.OLEDB.4.0; Data Source='{0}';" & "Extended Properties='Excel 8.0;HDR=YES;'", xlsFilePath))
conn.Open()
Dim strTableQ(ds.Tables.Count) As String
Dim i As Integer = 0
'making table query
For i = 0 To ds.Tables.Count - 1
strTableQ(i) = "CREATE TABLE [" & ds.Tables(i).TableName & "]("
Dim j As Integer = 0
For j = 0 To ds.Tables(i).Columns.Count - 1
Dim dCol As DataColumn
dCol = ds.Tables(i).Columns(j)
strTableQ(i) &= " [" & dCol.ColumnName & "] varchar(255) , "
Next
strTableQ(i) = strTableQ(i).Substring(0, strTableQ(i).Length - 2)
strTableQ(i) &= ")"
Using cmd As New OleDb.OleDbCommand(strTableQ(i), conn)
cmd.ExecuteNonQuery()
End Using
Next
'making insert query
Dim strInsertQ(ds.Tables.Count - 1) As String
For i = 0 To ds.Tables.Count - 1
strInsertQ(i) = "Insert Into " & ds.Tables(i).TableName & " Values ("
For k As Integer = 0 To ds.Tables(i).Columns.Count - 1
strInsertQ(i) &= "#" & ds.Tables(i).Columns(k).ColumnName & " , "
Next
strInsertQ(i) = strInsertQ(i).Substring(0, strInsertQ(i).Length - 2)
strInsertQ(i) &= ")"
Next
'Now inserting data
For i = 0 To ds.Tables.Count - 1
For j As Integer = 0 To ds.Tables(i).Rows.Count - 1
Using cmd As New OleDb.OleDbCommand(strInsertQ(i), conn)
For k As Integer = 0 To ds.Tables(i).Columns.Count - 1
cmd.Parameters.AddWithValue("#" & ds.Tables(i).Columns(k).ColumnName.ToString(), ds.Tables(i).Rows(j)(k).ToString())
Next
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
End Using
Next
Next
conn.Close()
Cursor.Current = Cursors.Default
End Using
End If
End Using
End Sub
Also note that a form that you display with ShowDialog() method must be disposed too.

DataGridView to CSV File

I have a VB 2010 Express Project, that has a DataGridView in it, that I am trying to write to a CSV file.
I have the write all working. But its slow. Slow = maybe 30 seconds for 6000 rows over 8 columns.
Here is my code:
Private Sub btnExportData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExportData.Click
Dim StrExport As String = ""
For Each C As DataGridViewColumn In DataGridView1.Columns
StrExport &= """" & C.HeaderText & ""","
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
For Each R As DataGridViewRow In DataGridView1.Rows
For Each C As DataGridViewCell In R.Cells
If Not C.Value Is Nothing Then
StrExport &= """" & C.Value.ToString & ""","
Else
StrExport &= """" & "" & ""","
End If
Next
StrExport = StrExport.Substring(0, StrExport.Length - 1)
StrExport &= Environment.NewLine
Next
Dim tw As IO.TextWriter = New IO.StreamWriter("C:\Test1.CSV")
tw.Write(StrExport)
tw.Close()
End Sub
Does anyone know what I can do to speed it up?
thanks
Don't you just love it when you spend hours searching, then post a question, and a few minutes later find the answer yourself?
This did the trick for me:
Dim headers = (From header As DataGridViewColumn In DataGridView1.Columns.Cast(Of DataGridViewColumn)() _
Select header.HeaderText).ToArray
Dim rows = From row As DataGridViewRow In DataGridView1.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("csv.txt")
sw.WriteLine(String.Join(",", headers))
For Each r In rows
sw.WriteLine(String.Join(",", r))
Next
End Using
Process.Start("csv.txt")