Monday, May 28, 2007

VB.NET: Data Grid View & Reading From CSV File

Oh my goodness. It's really been ages since I did VB programming. I am so so lost! Today's code:

Public Class frmReport

Private Sub btnGenerateReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenerateReport.Click

'Datagridview dgvReport settings
Me.Controls.Add(dgvReport)

dgvReport.ColumnCount = 5
With dgvReport.ColumnHeadersDefaultCellStyle
.ForeColor = Color.White
.Font = New Font(dgvReport.Font, FontStyle.Bold)
End With

With dgvReport
.Name = "dgvReport"
.Location = New Point(8, 8)
.Size = New Size(500, 250)
.AutoSizeRowsMode = _
DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single
.CellBorderStyle = DataGridViewCellBorderStyle.Single
.GridColor = Color.Black
.RowHeadersVisible = False

'Define top column names in dgvReport
.Columns(0).Name = "Date-Time"
.Columns(1).Name = "Action"
.Columns(2).Name = "Area"
.Columns(3).Name = "Section"
.Columns(4).Name = "Link"
.Columns(4).DefaultCellStyle.Font = _
New Font(Me.dgvReport.DefaultCellStyle.Font, FontStyle.Italic)

.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.MultiSelect = False
.Dock = DockStyle.Fill
End With

'Open file info.csv & read
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser _
("C:\Susanna's Work Stuff\Projects\DiGi\DiGi MDL\2007_05_28\reports\reports\bin\info.csv")

'Specify that reading from a comma-delimited file
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
With Me.dgvReport.Rows
.Add(currentRow) 'Add new row to dgvReport
End With
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using

End Sub

End Class

Got the chunk off 2 different MSDN pages. Thankfully it worked, after a bit of tweaking! Phew! All in a day's work...

No comments: