How to get online date in vb.net? - vb.net

How to get online date in vb.net ? is this possible ?
i use this code but it gives error like this (The remote server
returned an error: (503) Server Unavailable.) can anyone help ? thank you in advance
Imports System.ComponentModel
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Function getPageSource(ByVal URL As String) As String
Dim getWebClient As System.Net.WebClient = New System.Net.WebClient()
Dim strSource As String = getWebClient.DownloadString(URL)
getWebClient.Dispose()
Return strSource
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myPageSource, myStr, myStr1, strDate As String
Dim curLen, myStrPos, setStartPos As Integer
Dim dt As DateTime
txtPageSource.Text = getPageSource("http://www.worldtimeserver.com/current_time_in_PH.aspx")
myPageSource = txtPageSource.Text
'code to trim all the text till TIME start position
myStr = ""
myStrPos = myPageSource.IndexOf(myStr)
txtPageSource.Text = txtPageSource.Text.Remove(1, myStrPos + 23)
myPageSource = txtPageSource.Text
'code to trim all the text till after DATE
curLen = Len(txtPageSource.Text)
myStr1 = "2010"
setStartPos = myPageSource.IndexOf(myStr1)
txtPageSource.Text = txtPageSource.Text.Remove(setStartPos + 4, curLen - setStartPos - 4)
'code to trim "" and "" tags in between TIME and DATE
' 6:27 AM
'
'
'Wednesday, June 23, 2010
txtPageSource.Text = txtPageSource.Text.Replace("", "")
txtPageSource.Text = txtPageSource.Text.Replace("", "")
strDate = txtPageSource.Text
dt = CType((TypeDescriptor.GetConverter(New DateTime(2000, 1, 1)).ConvertFrom(strDate)), DateTime)
'txtPageSource.Text = dt
MsgBox(dt)
End Sub
End Class

Related

DateTimePicker: the box goes back to it's original date?

Hey guys so im doing a program for a zodiac finder on vb,The program works and all but my problem is that everytime I run it the DateTimePickerBox goes back to the current date instead of the date I have entered.
Here's my unfinished code;
Public Class HoroscopeSign
Private Sub HoroscopeSign_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'DateTimePicker.Format = DateTimePickerFormat.Custom
'DateTimePicker.CustomFormat = "dd MMMM yyyy"
txtDOB.Format = DateTimePickerFormat.Short
End Sub
Private Sub btnEnter_Click(sender As System.Object, e As System.EventArgs) Handles btnEnter.Click
Dim DOB As Date = txtDOB.Value
txtDOB.Text = Process(DOB)
End Sub
Public Function Process(dateOfBirth As Date) As String
Dim sign As String
Dim info As String
Dim BirthYear As Integer = dateOfBirth.Year
Dim BirthMonth As Integer = dateOfBirth.Month
Dim BirthDay As Integer = dateOfBirth.Day
If txtDOB.Value >= New Date(BirthYear, 1, 20) And txtDOB.Value <= New Date(BirthYear, 2, 18) Then
PBHoroscope.Load("E:\Aquarius.jpg")
sign = "Aquarius"
info = ""
Else txtDOB.Value >= New Date(BirthYear, 2, 19) And txtDOB.Value <= New Date(BirthYear, 3, 20) Then
PBHoroscope.Load("E:\Pisces.jpg")
sign = "Pisces"
lblSign.Text = sign
lblDescription.Text = info
End Function
Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
Dim a As Integer
a = MsgBox("Do you want to exit this application", vbYesNo, "Exit Application")
If a = vbYes Then
MsgBox("Thank you for using this application", vbOKOnly, "Exit Application")
End
Else
Me.Show()
End If
End Sub
Private Sub txtDOB_ValueChanged(sender As System.Object, e As System.EventArgs) Handles txtDOB.ValueChanged
Dim DOB As Date = txtDOB.Value
DOB = txtDOB.Value
End Sub
End Class
So you have declared your function Process to return a string, but you don't return anything from that function. The problem then arises when you try to assign the return value of that function to the txtDOB.Text property. You don't return anything and so the txtDOB resets itself to the current date
You should decide what string (in a date format) you want to return or better change your Process function to return a DateTime and assign that value to txtDOB.Value property. Or just change these lines to
Private Sub btnEnter_Click(sender As System.Object, e As System.EventArgs) Handles btnEnter.Click
' REMOVE THIS LINE Dim DOB As Date = txtDOB.Value
' REMOVE THIS LINE txtDOB.Text = Process(DOB)
Process(txtDOB.Value)
End Sub

Save clicks to file

I got asked a couple of days ago how to save number of clicks you have done to each button in a program to a small file, to keep track of what is most used. Since it was ages ago i dabbled with visual basic i said i would raise the question here, so here goes.
There are 5 buttons labels Button1-Button5. When a button is clicked it should look for the correct value in a file.txt and add +1 to the value. The file is structured like this.
Button1 = 0
Button2 = 0
Button3 = 0
Button4 = 0
Button5 = 0
So when button1 is clicked it should open file.txt, look for the line containing Button1 and add +1 to the value and close the file.
I have tried looking for some kind of tutorial on this but have not found it so i'm asking the collective of brains here on Stackoverflow for some guidance.
Thanks in advance.
delete file first
new ver ..
Imports System.IO.File
Imports System.IO.Path
Imports System.IO
Imports System.Text
Public Class Form1
Dim line() As String
Dim strbild As StringBuilder
Dim arr() As String
Dim i As Integer
Dim pathAndFile As String
Dim addLine As System.IO.StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fileName As String = "myfile.txt"
Dim appPath As String = My.Application.Info.DirectoryPath
pathAndFile = Path.Combine(appPath, fileName)
If System.IO.File.Exists(pathAndFile) Then
'line = File.ReadAllLines(pathAndFile)
Else
Dim addLineToFile = System.IO.File.CreateText(pathAndFile) 'Create an empty txt file
Dim countButtons As Integer = 5 'add lines with your desired number of buttons
For i = 1 To countButtons
addLineToFile.Write("Button" & i & " = 0" & vbNewLine)
Next
addLineToFile.Dispose() ' and close file
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
writeToFile(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
writeToFile(2)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
writeToFile(3)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
writeToFile(4)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
writeToFile(5)
End Sub
Public Sub writeToFile(buttonId As Integer)
Dim tmpButton As String = "Button" & buttonId
strbild = New StringBuilder
line = File.ReadAllLines(pathAndFile)
Dim f As Integer = 0
For Each lineToedit As String In line
If InStr(1, lineToedit, tmpButton) > 0 Then
Dim lineSplited = lineToedit.Split
Dim cnt As Integer = lineSplited.Count
Dim newVal = addCount(CInt(lineSplited.Last()))
lineSplited(cnt - 1) = newVal
lineToedit = String.Join(" ", lineSplited)
line(f) = lineToedit
End If
f = f + 1
Next
strbild = New StringBuilder
'putting together all the reversed word
For j = 0 To line.GetUpperBound(0)
strbild.Append(line(j))
strbild.Append(vbNewLine)
Next
' writing to original file
File.WriteAllText(pathAndFile, strbild.ToString())
Me.Refresh()
End Sub
' Reverse Function
Public Function ReverseString(ByRef strToReverse As String) As String
Dim result As String = ""
For i As Integer = 0 To strToReverse.Length - 1
result += strToReverse(strToReverse.Length - 1 - i)
Next
Return result
End Function
Public Function addCount(ByVal arr As Integer) As Integer
Return arr + 1
End Function
End Class
Output in myfile.txt
Button1 = 9
Button2 = 2
Button3 = 4
Button4 = 0
Button5 = 20
Create a vb winform Application
Drag on your form 5 buttons (Button1, Button2, ... etc)
copy that :
Imports System.IO.File
Imports System.IO.Path
Imports System.IO
Imports System.Text
Public Class Form1
Dim line() As String
Dim strbild As StringBuilder
Dim arr() As String
Dim i As Integer
Dim pathAndFile As String
Dim addLine As System.IO.StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fileName As String = "myfile.txt"
Dim appPath As String = My.Application.Info.DirectoryPath
pathAndFile = Path.Combine(appPath, fileName)
If System.IO.File.Exists(pathAndFile) Then
line = File.ReadAllLines(pathAndFile)
Else
Dim addLineToFile = System.IO.File.CreateText(pathAndFile) 'Create an empty txt file
Dim countButtons As Integer = 5 'add lines with your desired number of buttons
For i = 1 To countButtons
addLineToFile.Write("Button" & i & " = 0" & vbNewLine)
Next
addLineToFile.Dispose() ' and close file
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
writeToFile(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
writeToFile(2)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
writeToFile(3)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
writeToFile(4)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
writeToFile(5)
End Sub
Public Sub writeToFile(buttonId As Integer)
Dim tmpButton As String = "Button" & buttonId
strbild = New StringBuilder
line = File.ReadAllLines(pathAndFile)
i = 0
For Each lineToedit As String In line
If lineToedit.Contains(tmpButton) Then
Dim lineSplited = lineToedit.Split
Dim newVal = addCount(CInt(lineSplited.Last()))
'lineToedit.Replace(lineSplited.Last, newVal)
lineToedit = lineToedit.Replace(lineToedit.Last, newVal)
line(i) = lineToedit
End If
i = i + 1
Next
strbild = New StringBuilder
'putting together all the reversed word
For j = 0 To line.GetUpperBound(0)
strbild.Append(line(j))
strbild.Append(vbNewLine)
Next
' writing to original file
File.WriteAllText(pathAndFile, strbild.ToString())
End Sub
' Reverse Function
Public Function ReverseString(ByRef strToReverse As String) As String
Dim result As String = ""
For i As Integer = 0 To strToReverse.Length - 1
result += strToReverse(strToReverse.Length - 1 - i)
Next
Return result
End Function
Public Function addCount(ByVal arr As Integer) As Integer
Return arr + 1
End Function
End Class
Have fun ! :)CristiC777
try this on vs2013
change If confition
line = File.ReadAllLines(pathAndFile)
i = 0
For Each lineToedit As String In line
If InStr(1, lineToedit, tmpButton) > 0 Then
'If lineToedit.Contains(tmpButton) = True Then
Dim lineSplited = lineToedit.Split
Dim newVal = addCount(CInt(lineSplited.Last()))
lineToedit = lineToedit.Replace(lineToedit.Last, newVal)
line(i) = lineToedit
End If
i = i + 1
Next

code modified lines added

I have data like this
date value
24sep2014 2:23:01 0.1
24sep2014 2:23:02 0.3
24sep2014 2:23:03 0.2
24sep2014 2:23:04 0.3
These are not coma seprated value. I wanted to write in CSV file. Apend the value for next row.
1)How to open file only once here. when it run next time file name has to change to other name
2) How to append the next values
Imports System
Imports System.IO.Ports
Imports System.ComponentModel
Imports System.Threading
Imports System.Drawing
Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Dim myPort As Array
Dim Distance As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myPort = IO.Ports.SerialPort.GetPortNames()
PortComboBox.Items.AddRange(myPort)
BaudComboBox.Items.Add(9600)
BaudComboBox.Items.Add(19200)
BaudComboBox.Items.Add(38400)
BaudComboBox.Items.Add(57600)
BaudComboBox.Items.Add(115200)
ConnectButton.Enabled = True
DisconnectButton.Enabled = False
Chart1.Series.Clear()
Chart1.Titles.Add("Demo")
'Create a new series and add data points to it.
Dim s As New Series
s.Name = "CURRENT"
s.ChartType = SeriesChartType.Line
End Sub
Private Sub ConnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectButton.Click
SerialPort1.PortName = PortComboBox.Text
SerialPort1.BaudRate = BaudComboBox.Text
SerialPort1.Open()
Timer1.Start()
Timer2.Start()
'lblMessage.Text = PortComboBox.Text & " Connected."
ConnectButton.Enabled = False
DisconnectButton.Enabled = True
End Sub
Private Sub DisconnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisconnectButton.Click
SerialPort1.Close()
DisconnectButton.Enabled = False
ConnectButton.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim counter As Integer
counter = 0
Try
SerialPort1.Write("c")
System.Threading.Thread.Sleep(250)
Dim k As Double
Dim distance As String = SerialPort1.ReadLine()
k = CDbl(distance)
ListBoxSensor.Text = k
Dim s As New Series
s.Points.AddXY(1000, k)
Chart1.Series.Add(s)
Dim headerText = ""
Dim csvFile As String = Path.Combine(My.Application.Info.DirectoryPath, "Current.csv")
If Not File.Exists(csvFile)) Then
headerText = "Date& time ,Current"
End If
Using outFile = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
If headerText.Length > 0 Then
outFile.WriteLine(headerText)
End If
Dim y As String = DateAndTime.Now
Dim x As String = y + "," + distance
outFile.WriteLine(x)
End Using
Catch ex As Exception
End Try
End Sub
Private Sub Relay_ON_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Relay_ON.Click
SerialPort1.Write("1")
End Sub
Private Sub Relay_Off_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Relay_Off.Click
SerialPort1.Write("0")
End Sub
End Class
Here i am opening file again and again. that reason i can store only one value
# steve error
The second parameter of OpenTextFileWriter allows to append instead of overwrite your file.
So it is simply a matter to check if the file exists (so you insert the header names) and then write your data
Dim headerText = ""
Dim csvFile As String = Path.Combine(My.Application.Info.DirectoryPath, "Current.csv")
If Not File.Exists(csvFile) Then
headerText = "Date& time ,Current"
End If
Using outFile = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
If headerText.Length > 0 Then
outFile.WriteLine(headerText)
End If
Dim y As String = DateAndTime.Now
Dim x As String = y + "," + distance
outFile.WriteLine(x)
End Using
Notice the Using Statement to be sure to close and dispose the file resource also in case of exceptions.
However given the simple text that need to be written you could also choose to use the method WriteAllText
Dim headerText = ""
Dim csvFile As String = Path.Combine(My.Application.Info.DirectoryPath, "Current.csv")
If Not File.Exists(csvFile) Then
headerText = "Date& time ,Current" & Environment.NewLine
End If
Dim y As String = DateAndTime.Now
Dim x As String = headerText & y & "," + distance & Environment.NewLine
My.Computer.FileSystem.WriteAllText(csvFile, x, True)

I'm trying to read a .txt DataGridView in VB Express 2010 and search for contents. How do I do it? (content is relevant)

This is my first time on this site and I would like help very much.
I made a program in VB 2010 Express to try and read a .txt file into an DataGridView. I got it to read in and I have a function to search through surnames and search through date of birth. The way I want it to search is so that if I type in the month (02) for February, then it will list all the people with the DOB month as February. The surnames work fine but the DOB doesn't. Whenever I try to search the month February (02) The DataGridView becomes blank. http://puu.sh/8asUD.png (picture of addressgrid/datagridview going blank) The contents of the .txt file are exactly:
Jackson,Samantha,2 Heather Row,Basingstoke,RG21 3SD,01256 135434,23/04/1973,sam.jackson#hotmail.com,Vickers,Jonathan,18 Saville Gardens,Reading,RG3 5FH,01196 678254,04/02/1965,the_man#btinternet.com,Morris,Sally,The Old Lodge, Hook,RG23 5RD,01256 728443,19/02/1975,smorris#fgh.co.uk,Cobbly,Harry,345 The High Street,Guildford,GU2 4KJ,01458 288763,30/03/1960,harry.cobbly#somewhere.org.uk,Khan,Jasmine,36 Hever Avenue,Edenbridge,TN34 4FG,01569 276524,28/02/1980,jas.khan#hotmail.com,Vickers,Harriet,45 Sage Gardens,Brighton,BN3 2FG,01675 662554,04/04/1968,harriet.vickers#btinternet.com
Here's the code for THE ENTIRE FORM:
Public Class AddressBook
Structure Address
Public Forename As String
Public Surname As String
Public Address1 As String
Public Address2 As String
Public Postcode As String
Public Phonenumber As String
Public DOB As String
Public Email As String
End Structure
Public Addressbook(40) As Address
Public recordcounter As Integer = 0
Public readfile As Boolean = False
Private Sub btt_read_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btt_read.Click
'Declare Textfile
If System.IO.File.Exists("addressbook.txt") = False Then
MsgBox("This text file doesn't exist")
End If
Dim Addressfile As New System.IO.StreamReader("C:\Users\DirtyMike\Desktop\123\Controlled Assessment\addressbook.txt", True)
Dim loopcounter As Integer
Dim filecontent As String
Dim temparray() As String
If readfile = False Then
filecontent = Addressfile.ReadLine
temparray = filecontent.Split(",")
readfile = True
'Display the data
For loopcounter = 0 To (temparray.Length - 7) Step 8
Addressbook(recordcounter).Surname = temparray(loopcounter + 0)
Addressbook(recordcounter).Forename = temparray(loopcounter + 1)
Addressbook(recordcounter).Address1 = temparray(loopcounter + 2)
Addressbook(recordcounter).Address2 = temparray(loopcounter + 3)
Addressbook(recordcounter).Postcode = temparray(loopcounter + 4)
Addressbook(recordcounter).Phonenumber = temparray(loopcounter + 5)
Addressbook(recordcounter).DOB = temparray(loopcounter + 6)
Addressbook(recordcounter).Email = temparray(loopcounter + 7)
recordcounter = recordcounter + 1
Next
Addressfile.Close()
REM Display the Data
For loopcounter = 0 To recordcounter - 1
AddressGrid.Rows.Add()
AddressGrid.Rows.Item(loopcounter).Cells(0).Value = Addressbook(loopcounter).Surname
AddressGrid.Rows.Item(loopcounter).Cells(1).Value = Addressbook(loopcounter).Forename
AddressGrid.Rows.Item(loopcounter).Cells(2).Value = Addressbook(loopcounter).Address1
AddressGrid.Rows.Item(loopcounter).Cells(3).Value = Addressbook(loopcounter).Address2
AddressGrid.Rows.Item(loopcounter).Cells(6).Value = Addressbook(loopcounter).DOB
AddressGrid.Rows.Item(loopcounter).Cells(7).Value = Addressbook(loopcounter).Email
AddressGrid.Rows.Item(loopcounter).Cells(5).Value = Addressbook(loopcounter).Phonenumber
AddressGrid.Rows.Item(loopcounter).Cells(4).Value = Addressbook(loopcounter).Postcode
Next
'Display the data from the file.
End If
End Sub
Private Sub bttsurname_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btt_searchsur.Click
AddressGrid.Rows.Clear()
Dim surname As String
Dim loopcounter As Integer
Dim positioncounter As Integer
surname = txt_surname.Text
For loopcounter = 0 To recordcounter
If Addressbook(loopcounter).Surname = surname Then
Me.AddressGrid.Rows.Add()
Me.AddressGrid.Rows.Item(positioncounter).Cells(0).Value = Me.Addressbook(loopcounter).Surname
Me.AddressGrid.Rows.Item(positioncounter).Cells(1).Value = Me.Addressbook(loopcounter).Forename
Me.AddressGrid.Rows.Item(positioncounter).Cells(2).Value = Me.Addressbook(loopcounter).Address1
Me.AddressGrid.Rows.Item(positioncounter).Cells(3).Value = Me.Addressbook(loopcounter).Address2
Me.AddressGrid.Rows.Item(positioncounter).Cells(4).Value = Me.Addressbook(loopcounter).Postcode
Me.AddressGrid.Rows.Item(positioncounter).Cells(5).Value = Me.Addressbook(loopcounter).Phonenumber
Me.AddressGrid.Rows.Item(positioncounter).Cells(6).Value = Me.Addressbook(loopcounter).DOB
Me.AddressGrid.Rows.Item(positioncounter).Cells(7).Value = Me.Addressbook(loopcounter).Email
positioncounter = positioncounter + 1
End If
Next
End Sub
Private Sub btt_menu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btt_menu.Click
Menu1.Show()
Me.Close()
End Sub
Private Sub btt_searchdob_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btt_searchdob.Click
AddressGrid.Rows.Clear()
Dim DOB As String
Dim loopcounter, positioncounter As Integer
Dim MonthA As String
DOB = txt_DOB.Text
MonthA = Mid(DOB, 4, 2)
positioncounter = 0
For loopcounter = 0 To recordcounter
If MonthA = Mid(Addressbook(loopcounter).DOB, 4, 2) Then
Me.AddressGrid.Rows.Add()
Me.AddressGrid.Rows.Item(positioncounter).Cells(0).Value = Me.Addressbook(loopcounter).Surname
Me.AddressGrid.Rows.Item(positioncounter).Cells(1).Value = Me.Addressbook(loopcounter).Forename
Me.AddressGrid.Rows.Item(positioncounter).Cells(2).Value = Me.Addressbook(loopcounter).Address1
Me.AddressGrid.Rows.Item(positioncounter).Cells(3).Value = Me.Addressbook(loopcounter).Address2
Me.AddressGrid.Rows.Item(positioncounter).Cells(4).Value = Me.Addressbook(loopcounter).Postcode
Me.AddressGrid.Rows.Item(positioncounter).Cells(5).Value = Me.Addressbook(loopcounter).Phonenumber
Me.AddressGrid.Rows.Item(positioncounter).Cells(6).Value = Me.Addressbook(loopcounter).DOB
Me.AddressGrid.Rows.Item(positioncounter).Cells(7).Value = Me.Addressbook(loopcounter).Email
positioncounter = positioncounter + 1
End If
Next
End Sub
Private Sub btt_clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btt_clear.Click
AddressGrid.Rows.Clear()
For loopcounter = 0 To recordcounter - 1
AddressGrid.Rows.Add()
AddressGrid.Rows.Item(loopcounter).Cells(0).Value = Addressbook(loopcounter).Surname
AddressGrid.Rows.Item(loopcounter).Cells(1).Value = Addressbook(loopcounter).Forename
AddressGrid.Rows.Item(loopcounter).Cells(2).Value = Addressbook(loopcounter).Address1
AddressGrid.Rows.Item(loopcounter).Cells(3).Value = Addressbook(loopcounter).Address2
AddressGrid.Rows.Item(loopcounter).Cells(4).Value = Addressbook(loopcounter).Postcode
AddressGrid.Rows.Item(loopcounter).Cells(5).Value = Addressbook(loopcounter).Phonenumber
AddressGrid.Rows.Item(loopcounter).Cells(6).Value = Addressbook(loopcounter).DOB
AddressGrid.Rows.Item(loopcounter).Cells(7).Value = Addressbook(loopcounter).Email
Next
'Display the data from the file.
End Sub
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
Any help would be greatly appreciated. Thanks in advance! (P.S. Apologies for the poor tags, they're probably wrong.)
If you can add some Symbol into the text this process will be easy to fetch Like:
TextFileData = %Your Name,Age,Address%Other Name, Other Age, Other Address,
You can use split ("%") to get the users information
Users = TextFileData.Split("%")
Then use split(",") to extract the information
Information = Users(0),Split(",")

Reading from and manipulating a .csv file

I have multiple .csv files for each month which go like:
01/04/2012,00:00,7.521527,80.90972,4.541667,5.774305,7,281.368
02/04/2012,00:00,8.809029,84.59028,6.451389,5.797918,7,274.0764
03/04/2012,00:00,4.882638,77.86806,1.152778,15.13611,33,127.6389
04/04/2012,00:00,5.600694,50.35417,-3.826389,15.27222,33,40.05556
The format is : Date in the form dd/mm/yy,Current time,Current temperature,Current humidity,Current dewpoint,Current wind speed,Current wind gust,Current wind bearing
The program needs to calculate the average for
temperature
humidity
wind speed
wind direction
and display them on a text box.
any ideas?
Here is what I have done so far...
Option Strict On
Option Explicit On
Imports System.IO
Imports System
Public Class Form1
Private Sub cmb1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmb1.SelectedIndexChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnexit.Click
Me.Close()
End Sub
Private Sub btn1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndata.Click
'This is for August
If cmb1.SelectedIndex = 1 Then
TextBox1.Clear()
Using reader As New StreamReader("c://temp/DailyAug12log.csv")
Dim line As String = reader.ReadLine()
Dim avgTemp As Integer
Dim fields() As String = line.Split(",".ToCharArray())
Dim fileDate = CDate(fields(0))
Dim fileTime = fields(1)
Dim fileTemp = fields(2)
Dim fileHum = fields(3)
Dim fileWindSpeed = fields(4)
Dim fileWindGust = fields(5)
Dim fileWindBearing = fields(6)
While line IsNot Nothing
counter = counter + 1
line = reader.ReadLine()
End While
avgTemp = CInt(fields(2))
avgTemp = CInt(CDbl(avgTemp / counter))
TextBox1.Text = TextBox1.Text & "Month = August" & vbCrLf & "Temperature Average: " & avgTemp & vbCrLf
End Using
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim files() As String
files = Directory.GetFiles("C:\Temp", "*.csv", SearchOption.AllDirectories)
For Each FileName As String In files
cmb1.Items.Add(FileName.Substring(FileName.LastIndexOf("\") + 1, FileName.Length - FileName.LastIndexOf("\") - 1))
Next
End Sub
End Class
Private Class Weather
Public SampleTimeStamp AS Date
Public Temperature AS Double
Public Humidity As Double
Public WindSpeed AS Double
Public WindBearing AS Double
End Class
Sub Main
Dim samples = ReadFile("c://temp/DailyAug12log.csv")
Dim avgTemperature = samples.Average(Function(s) s.Temperature)
...
End Sub
Private Function ReadFile(ByVal fileName as String) AS List(Of Weather)
Dim samples As New List(Of Weather)
Using tfp As new TextFieldParser(filename)
tfp.Delimiters = new String() { "," }
tfp.TextFieldType = FieldType.Delimited
While Not tfp.EndOfData
Dim fields = tfp.ReadFields()
Dim sample As New Weather()
sample.SampleTimeStamp = Date.ParseExact(fields(0) & fields(1), "dd\/MM\/yyyyHH\:mm", CultureInfo.InvariantCulture)
sample.Temperature = Double.Parse(fields(2), CultureInfo.InvariantCulture)
sample.Humidity = Double.Parse(fields(3), CultureInfo.InvariantCulture)
sample.WindSpeed = Double.Parse(fields(4), CultureInfo.InvariantCulture)
sample.WindBearing = Double.Parse(fields(5), CultureInfo.InvariantCulture)
samples.Add(sample)
End While
Return samples
End Using
End Function
I would not use a this aprroach - if the order of the columns changes, your program will show wrong results.
I would use a good csv reader like http://kbcsv.codeplex.com/ and read the Data to a datatable. then you can calculate your resulting columns quite easily and reliablly, because you can adress each column like MyDatatable.Cooumns["Headername"].