|
Question : VB.net opening text file into DataGridView
|
|
Hi
I am trying to use the code at in the function at the end of this text to open a text file into a DataGridView before opening it into Excel using the Workbooks.OpenText. I am not sure how to make provision in the parser for all the properties of the OpenText method as held in the variables below, especially multiple delimiters xlApp.Workbooks.OpenText(oFilename, Excel.XlPlatform.xlWindows, oStartRow, oDataType, oTextQualifier, oConsecutiveDelimiter, oTab, oSemicolon, oComma, oSpace, oOther, oOtherCharacter, oFieldInfo, oTextVisualLayout, oDecimalSeparator, oThousandsSeparator, oTrailingMinusNumbers, oLocal)
Public Function ReadFileToDGV(ByVal fileName As String) As DataTable 'assign to datagridview ' Initialize the return values Dim dt As New DataTable
Using parser As New TextFieldParser(fileName)
' Setup the comma-delimited file parser. parser.TextFieldType = FieldType.Delimited parser.Delimiters = New String() {","} parser.HasFieldsEnclosedInQuotes = True
While Not parser.EndOfData Try ' Read the comma-delimited text as fields into a string array. Dim input As String() = parser.ReadFields()
'add the columns to the DataTable if they do not exist If dt.Columns.Count = 0 Then For i As Integer = 0 To input.Length - 1 dt.Columns.Add("Field" & i + 1) Next End If
'create a new DataRow Dim dr As DataRow = dt.NewRow
'fill the datarow with the row values dr.ItemArray = input
'add the datarow to the DataTable dt.Rows.Add(dr)
Catch ex As MalformedLineException ' Ignore mal-formed lines. End Try End While
End Using
Return dt
End Function
|
|
Answer : VB.net opening text file into DataGridView
|
|
There are a lot of holes in that type of processing. If you had mentioned this requirement before, I would have suggested a different approach.
Bob
|
|
|
|