Reputation: 85
delimited files what i need is to read from a comma-delimited file and retrieve ownley certain lines off them to a combobox, the combobox must then ownley show destinct names. I added a database-working code below of what im looking for but instaed of using a database i need the code for comma-delimeted files.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call combo1()
End Sub
Sub combo1()
Dim com As SqlConnection
com = New SqlConnection("Server = Q-DESIGN\SQLEXPRESS; Database = Q-Design Test Results; Trusted_Connection = true;")
com.Open()
Dim command As SqlCommand = New SqlCommand("SELECT DISTINCT(Testname) from URL", com)
Dim reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
ComboBox1.Items.Add(reader.GetString(0))
End While
reader.Close()
com.Dispose()
com.Close()
End Sub
My comma delimited file will have the following lines for egsample
Jenny, 25, Female
Micheal, 100, Female
shaun, 50, male
Cindy, 75, Female
Cindy, 30, Female
Cindy, 20, Female
Micheal, 30, Female
deric, 50, Male
I need the combobox to show every name, ownley once
Upvotes: 0
Views: 365
Reputation: 151
First I would read in the file one line at a time. I would then use regular expressions to extract the name field your looking for. Next I would add each item to a SortedSet.
Dim strLine as String = ""
Dim RX as New Regex("^([^,]*),")
Dim MyMatch as Match
Dim NameLookup as New SortedSet(Of String)
'
' Code to read in each line into strLine using StreamReader.
'
MyMatch = RX.Match(strLine)
If MyMatch.Success AndAlso Not NameLookUp.Contains(MyMatch.Result("${1}")) Then
NameLookup.Add(MyMatch.Result("${1}"))
End If
After this adding the items from the SortedSet to the ComboBox should be fairly easy.
Also you can also manually create a DataTable with a "Name" column and use data bindings to automatically populate the combobox.
Upvotes: 0
Reputation: 101052
You can use a TextFieldParser
and a HastSet
.
Here's a simple example:
' a set to store the names
Dim names = new HashSet(Of String)
Using reader = New Microsoft.VisualBasic.FileIO.TextFieldParser("c:\your\path")
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {","}
Dim currentRow As String()
While Not reader.EndOfData
Try
' read rows and add first field to set
currentRow = reader.ReadFields()
names.Add(currentRow(0).ToString())
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
' do something
End Try
End While
End Using
' bind data to combo box (or use Items.Add instead)
comboBox.DataSource = names.ToList()
Upvotes: 2