|
Hi,
I am new to VB.net programming and was wondering if anybody has any suggestions as to how I can export data from a DataGridView via a command button to a CSV file.
Any suggestions or sample code would be really appreciated.
Many thank.
Paul.
Hi, I was working with CSV file and DataGridView in VB.NET. Having lots fo complexities i succeeded to retrieve a 5 columns CSV file into DataGridView. It is to be mentioned that the last two columns in the dgv are Combo type.
My goal was after retrieving the csv file I will edit other two selection columns and export the modified file in a different locations.
the content of the CSV file is as follows:
2014001,"Mensch, Samantha",CD Models Christian values,S,*
2014001,"Mensch, Samantha",CD Shows reverence during pray,S,
2014001,"Mensch, Samantha",CD Accepts responsibility for,S,
2014001,"Mensch, Samantha",CD Practices self control,S,
2014001,"Mensch, Samantha",CD Observes school rules,S,*
2014001,"Mensch, Samantha",CD Respects property,S,
2014001,"Mensch, Samantha",CD Respects others,S,
2014001,"Mensch, Samantha",Uses time wisely,S,
2014001,"Mensch, Samantha",Displays effort,S,
2014001,"Mensch, Samantha",Works well in a group,S,
2014001,"Mensch, Samantha",Works well independently,S,
Code for the Reading CSV file as follows under a button:
Sub Action_Button
Dim lineNumber As Integer = 0
Dim line As String
Dim lToken() As String
Dim sTemp As String
Dim sGridRow(4) As String
OpenFileDialog1.InitialDirectory = "c:\temp\"
'openFileDialog1.Filter = "All files (*.*)|*.*"
OpenFileDialog1.Filter = "CSV files (*.csv)|*.CSV"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
Me.Text = fName
End If
Me.Text = fName
Try
Dim reader As IO.StreamReader = New IO.StreamReader(fName)
'DataGridView2.Rows.Remove()
DataGridView2.Rows.Clear()
While reader.Peek <> -1
line = reader.ReadLine()
lToken = Split(line, ",")
For i As Integer = 0 To lToken.Length - 3
sTemp = Replace(lToken(i), """", "")
sGridRow(i) = sTemp
Next
Me.DataGridView2.Rows.Add(sGridRow)
lineNumber += 1
End While
'Me.Text = Str(lineNumber)
reader.Close()
Catch ex As Exception
MessageBox.Show("Error occured while reading the csv file." + ex.ToString)
End Try
End Sub
The above code works fine, Please see the attached.
Now I face the problem after modifying the row in the dgv; suppose I have selected a grade from the combo. Now I want to export the file in a selected location as with the same name as I imported.
I can import the file taking the data from the dvg. I gave the code here to populate the dvg rows. I need entire dvg data to read and write them in the file.
The code I don know...How to take the data from the dbg from the first row to the last? The code I wrote is pasted here, but it simply populates the current row column.
Private Sub SaveGridDataInFile(ByRef fName As String)
'Dim writer As IO.StreamWriter = New IO.StreamWriter(fName)
Dim I As Integer = 0
Dim j As Integer = 0
Dim cellvalue$
Dim rowLine As String = ""
Try
FileOpen(1, fName, OpenMode.Output) ' Open file for output.
'WriteLine(1, "Hello", " ", "World") ' Separate strings with space.
'WriteLine(1, SPC(5), "5 leading spaces ") ' Print five leading spaces.
'WriteLine(1, TAB(10), "Hello") ' Print word at column 10.
'FileClose(1) ' Close file.
'sData = DataGridView1.Columns(1).Name.ToString()
'sData = Me.DataGridView1.CurrentRow.Cells(i).Value.ToStrin g
'MessageBox.Show(sData)
For j = 0 To (DataGridView2.Rows.Count - 2)
For I = 0 To (DataGridView2.Columns.Count - 1)
If Not TypeOf DataGridView2.CurrentRow.Cells.Item(I).Value Is DBNull Then
cellvalue = DataGridView2.CurrentRow.Cells.Item(I).Value.ToStr ing
Else
cellvalue = ""
End If
'DataGridView2.CurrentRow.Cells.Item(I).Value = cellvalue
rowLine = rowLine + cellvalue + ","
Next
WriteLine(1, TAB(0), rowLine) ' Print word at column 10.
'writer.WriteLine()
rowLine = ""
Next
FileClose(1) ' Close file.
Catch e As Exception
MessageBox.Show("Error occured while writing to the file." + e.ToString())
Finally
FileClose(1)
End Try
End Sub
Could you please help me giving the code that reads entire row column of the dvg?
At last i succeeded. That is I populated the datagridview control with the following syntax:
For j = 0 To (DataGridView2.Rows.Count - 2)
For I = 0 To (DataGridView2.Columns.Count - 1)
If Not TypeOf DataGridView2.Item(I, j).Value Is DBNull Then
cellvalue = DataGridView2.Item(I, j).Value Else
cellvalue = ""
End If
rowLine = rowLine + "" & Chr(34) & cellvalue & Chr(34) + ","
Next
rowLine = rowLine.Remove(rowLine.Length - 1, 1)
sw.WriteLine(rowLine)
rowLine = ""
Next
Now I can export CSV file from datagrideview to a formated text file.
[EMAIL REMOVED]
Please give the subject of the email: CSF file Handler.
Thanks and regards
Shahidul Haque.
Yes I did get a solution to my problem...I know the code may seem a little complicated but it works a treat, obviously you will need to tweak any data but this is the code I needed for my solution.
Private Sub btnExportData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExportData.Click
Dim fsStream As New FileStream("C:\Temp\Test Results_" & txtTestSpecID.Text & "_" & cboTestPhase.Text & ".csv", FileMode.Append, FileAccess.Write)
Dim swWriter As New StreamWriter(fsStream)
Dim TotalPasses1 As Integer = 0
Dim TotalFails1 As Integer = 0
Dim TotalNA1 As Integer = 0
'Displays a Message Box informing the user you are about to Quit the application
Dim intReturnValue1 As Integer
intReturnValue1 = MsgBox("Data Saved Successfully", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Data Saved")
Try
CheckSave()
swWriter.WriteLine("Database, Test Spec ID, System, Version, Test Phase, Sites, Date/Time, Tester, Witness,Test Number, Test Step, Step 1, Step 2, Pass, Fail, N/A, Fault Reference,Fault Category,Comments,")
Dim temp As Integer = 0
For temp = 0 To grdResults.Rows.Count - 1
swWriter.Write(lblTestsSpec.Text & "," & txtTestSpecID.Text & "," & cboSystem.Text & "," & txtVersion.Text & "," & cboTestPhase.Text & "," & cboSites.Text & "," & txtDateTime.Text & "," & txtTester.Text & "," & txtWitness.Text & ",")
Dim temp2 As Integer = 0
For temp2 = 0 To grdResults.Rows(temp).Cells.Count - 1
If IsDBNull((grdResults.Rows.Item(temp).Cells.Item(te mp2).Value)) Then
Else
If (grdResults.Rows.Item(temp).Cells.Item(temp2).Valu e) = "True" Then
swWriter.Write("1")
If temp2 = 4 Then
TotalPasses1 = TotalPasses1 + 1
End If
If temp2 = 5 Then
TotalFails1 = TotalFails1 + 1
End If
If temp2 = 6 Then
TotalNA1 = TotalNA1 + 1
End If
ElseIf (grdResults.Rows.Item(temp).Cells.Item(temp2).Valu e) = "False" Then
swWriter.Write("")
Else
swWriter.Write(grdResults.Rows.Item(temp).Cells.It em(temp2).Value)
End If
End If
swWriter.Write(",")
Next
swWriter.WriteLine(",")
Next
swWriter.WriteLine("," & "," & "," & "," & "," & "," & "," & "," & "," & "," & "," & "," & "," & TotalPasses1 & "," & TotalFails1 & "," & TotalNA1 & ",")
swWriter.Flush()
MsgBox("Data Saved Successfully")
swWriter.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
First of all thank u very much for giving some solution.
Actual my moto is to save the datagridvalues in any file(.txt /.csv).
I have already able to save the data in .txt file by using the simple code mentioned below:
using (StreamWriter MyFile = new StreamWriter(Application.StartupPath+"\\About File Log.txt"))
{
for (int i = 0; i < dataGridView1.RowCount; i++)
{
MyFile.WriteLine("File Name: " + FinalDirs[i] + ", " + "File Version: " + FinalVers[i] + ", " + "File Size: " + FinalSize[i] + ", " + "Description: " + FinalDesc[i]);
MyFile.WriteLine("");
// Arbitrary objects can also be written to the file.
}
MyFile.Write("This file generated on: ");
MyFile.WriteLine(DateTime.Now);
MessageBox.Show("Information of all the files are successfully saved in the following location: \n"+Application.StartupPath+"\\AboutFileLog.txt", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
Close();
}
}
|