I have a textfile (data.txt) with 3 columns, each column with one variable (x1, x2 and x3). I would like to calculate a number of columns and show in a specific textbox (like textbox1). For example. My data.txt:
x1 x2 x3
10 15 20
20 10 10
TextBox1 needs to show: 3
CodePudding user response:
You use delimiter like present in the file. I use Space here
Sub test1()
Dim FileNum As Integer
Dim DataLine As String
FileNum = FreeFile()
Filename = "C:\test.txt"
Open Filename For Input As #FileNum
Lines = Split(Input$(LOF(FileNum), #FileNum), vbNewLine)
colnum = Split(Lines(1), " ")
MsgBox "No of Columns in the file is " & UBound(colnum) 1
End Sub
CodePudding user response:
Text files don't have columns. What you have is a file where each line separates elements by a space and each row is separated by a CR/LF (carraige return/line feed) To work with the text file put
Imports System.IO
at the top of the code file.
I am guessing that you will want to do more with the file than just determin the number of "columns" so, we will read the entire file. File.ReadAllLines() returns an array of lines in the file.
We take the first line in the file (index 0) and split it by a space. The lowere case c followint " " tells the compiler that you mean a Char not a String. Then we take the Length of the resulting array to find the number of columns.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lines = File.ReadAllLines("C:\Users\******\Desktop\Code\OPdata.txt")
Dim NoOfColumns = lines(0).Split(" "c).Length
TextBox1.Text = NoOfColumns.ToString
'Some other things you can do
Dim dt As New DataTable
Dim columns = lines(0).Split(" "c)
dt.Columns.Add(columns(0), GetType(Integer))
dt.Columns.Add(columns(1), GetType(Integer))
dt.Columns.Add(columns(2), GetType(Integer))
For index = 1 To lines.Length - 1
Dim values = lines(index).Split(" "c)
dt.Rows.Add({values(0), values(1), values(2)})
Next
DataGridView1.DataSource = dt
End Sub