Duplicating items on listbox - vb.net

I have a program that records homework in a list box, and sorts it by the date it is due. However, when I try to sort the data by date, it does so, but duplicates each item in the list box. This can be rectified by closing the program and opening it again, but this is very inconvenient. Is there any way to fix this?
Here is the code for the two
frmSplashScreen:
Imports System.IO
Public Class frmSplashscreen
Dim dates() As Date = {}
Dim temparray() As String = {}
Dim temparray2() As String = {}
Dim Path As String = Application.StartupPath
Dim newuser As Boolean = False
Dim sorted As Boolean = False
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
If lstDate.Items.Contains("No assignments yet!") Then
lstDate.Items.Clear()
End If
frmAdd.Show()
Me.Hide()
End Sub
Private Sub Me_mouseenter(sender As Object, e As EventArgs) Handles Me.MouseEnter
If sorted = False And lstDate.Items.Contains("No assignments yet!") = False Then
SortByDate()
End If
End Sub
Private Sub frmSplashscreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If File.Exists(Path & "Assignments.crw") = False Then
newuser = True
lstDate.Items.Add("No assignments yet!")
Else
FileOpen(1, Path & "Assignments.crw", OpenMode.Input)
While Not EOF(1)
Dim output As String = LineInput(1)
lstAssignments.Items.Add(Mid(output, InStr(output, "-") + 1, InStr(output, "_") - (InStr(output, "-") + 1)))
lstAN.Items.Add(Mid(output, InStr(output, "_") + 1, output.Length))
lstDate.Items.Add(Mid(output, 1, InStr(output, "-") - 1))
Array.Resize(temparray, temparray.Length + 1)
temparray(temparray.Length - 1) = output
End While
End If
FileClose(1)
If lstDate.Items.Contains("No assignments yet!") = False Then
SortByDate()
End If
End Sub
Private Sub SortByDate()
For Each x In lstDate.Items
MsgBox(x)
Array.Resize(dates, dates.Length + 1)
dates(dates.Length - 1) = x
Next
Array.Sort(dates)
' Sort dates.
temparray2 = {}
' Empty temparray2 for resizing
Dim counter As Integer = 0
' Declare counter
For Each x In dates
' Looping through dates...
Dim result As Integer
' ...Declare result.
For Each y In temparray
' Nestled for loop to check each result against one another. This time looping through temparray.
result = InStr(y, x)
' Search for x (The date) in y (the line of the file)
If result <> 0 Then
' If it is found...
Array.Resize(temparray2, temparray2.Length + 1)
counter = counter + 1
temparray2(counter - 1) = y
' Add y to the array temparray2 in chronological order.
End If
Next
Next
Dim num As Integer = 0
' Declare num
lstAN.Items.Clear()
lstAssignments.Items.Clear()
lstDate.Items.Clear()
temparray = {}
lstAN.Items.Clear()
lstAssignments.Items.Clear()
lstDate.Items.Clear()
For Each x In temparray2
Array.Resize(temparray, temparray2.Length)
temparray(num) = x
lstAssignments.Items.Add(Mid(x, InStr(x, "-") + 1, InStr(x, "_") - (InStr(x, "-") + 1)))
lstAN.Items.Add(Mid(x, InStr(x, "_") + 1, x.Length))
lstDate.Items.Add(Mid(x, 1, InStr(x, "-") - 1))
num += 1
Next
' Loop through temparray2 making temparray the exact same and adding the array to the listbox.
sorted = True
End Sub
Private Sub SortMyLife()
If File.Exists(Path & "Assignments.crw") = False Then
newuser = True
lstDate.Items.Add("No assignments yet!")
Else
FileOpen(1, Path & "Assignments.crw", OpenMode.Input)
While Not EOF(1)
Dim output As String = LineInput(1)
lstAssignments.Items.Add(Mid(output, InStr(output, "-") + 1, InStr(output, "_") - (InStr(output, "-") + 1)))
lstAN.Items.Add(Mid(output, InStr(output, "_") + 1, output.Length))
lstDate.Items.Add(Mid(output, 1, InStr(output, "-") - 1))
Array.Resize(temparray, temparray.Length + 1)
temparray(temparray.Length - 1) = output
End While
End If
FileClose(1)
If lstDate.Items.Contains("No assignments yet!") = False Then
SortByDate()
End If
End Sub
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked = True Then
Call SortMyLife()
CheckBox1.Checked = False
End If
End Sub
End Class
frmAdd (for adding a new assignment)
Public Class frmAdd
Dim temparray() As String = {}
Dim temparray2() As String = {}
Dim dates() As Date = {}
Dim sorted As Boolean
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim datedue As Date = dtpDue.Text
Dim Subject As String = cbxSbjct.Text
Dim Additional As String = rtfAN.Text
Dim Path As String = Application.StartupPath & "Assignments.crw"
If datedue > Now() Then
If Subject <> "Choose a subject" Then
FileOpen(1, Path, OpenMode.Append)
Dim output As String = dtpDue.Text & "-" & Subject & "_" & Additional
If frmSplashscreen.lstAssignments.Items.Contains("No assignments yet!") Then
frmSplashscreen.lstAssignments.Items.Clear()
frmSplashscreen.lstDate.Items.Clear()
frmSplashscreen.lstAN.Items.Clear()
End If
frmSplashscreen.lstAssignments.Items.Add(Mid(output, InStr(output, "-") + 1, InStr(output, "_") - (InStr(output, "-") + 1)))
frmSplashscreen.lstAN.Items.Add(Mid(output, InStr(output, "_") + 1, output.Length))
frmSplashscreen.lstDate.Items.Add(dtpDue.Text)
PrintLine(1, output)
FileClose(1)
For Each x In frmSplashscreen.lstDate.Items
MsgBox(x)
Next
Me.Close()
frmSplashscreen.Show()
Else
MsgBox("Please enter a subject in the box provided")
End If
Else
MsgBox("Please enter a date in the future", vbInformation, "Error")
End If
End Sub
End Class
Thank you for the help!

Have you tried something as simple as ListBoxHoliday.Items.Clear before the sort happens?

Related

VB service export SQL to CSV

I have created a service that is supposed to pass data from SQL to CSV, by creating a CSV file. It has no errors, but i run it and nothing happens.
1) Is there something I am missing?
2) If it works, and i want to convert to txt file, is it enough to change the "CSV" to "txt" parts?
My code:
#Region "Export SQL TO CSV"
Public Shared Function WriteCSV(ByVal input As String) As String
Try
If (input Is Nothing) Then
Return String.Empty
End If
Dim containsQuote As Boolean = False
Dim containsComma As Boolean = False
Dim len As Integer = input.Length
Dim i As Integer = 0
Do While ((i < len) _
AndAlso ((containsComma = False) _
OrElse (containsQuote = False)))
Dim ch As Char = input(i)
If (ch = Microsoft.VisualBasic.ChrW(34)) Then
containsQuote = True
ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
containsComma = True
End If
i = (i + 1)
Loop
If (containsQuote AndAlso containsComma) Then
input = input.Replace("""", """""")
End If
If (containsComma) Then
Return """" & input & """"
Else
Return input
End If
Catch ex As Exception
Throw
End Try
End Function
Private Sub ExtoCsv(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As StringBuilder = New StringBuilder
Using db As Database.RecordSet = admin.Database.OpenRecordsetReadOnly("select USERID, NAME1 from usertable WHERE I_ID=2")
Dim userid As String = db("USERID").Value
Dim name1 As String = db("NAME1").Value
For i As Integer = 1 To db.RecordCount
sb.Append(WriteCSV(userid + "," + name1 + ","))
sb.AppendLine()
db.MoveNext()
Next
End Using
File.WriteAllText("C:\Users\user1\Desktop\ex1.csv", sb.ToString)
If (Not System.IO.Directory.Exists("C:\Users\user1\Desktop\ex1")) Then
System.IO.Directory.CreateDirectory("C:\Users\user1\Desktop\ex1")
End If
End Sub
#End Region

VB2010 reading a text file into a datagridview but only certain fields/lines

I am trying to read through a text file but then displaying ONLY certain fields back to my DataGridView, not the whole file. I set the delimiter as " + " and then want to show the file where the field starts with for example EQD.
My file looks something like this where each line is sepearted by a " ' ":
UNB+UNOA:1+++160804:0850+1+++++1'
UNH+402+BAPLIE:1:911:UN:SMDG15'
BGM++580691+9'
DTM+137:2016080408 50:301'
TDT+20+6217++++MACS:172:166'
LOC+5+NAWVB:139:6'
LOC+61+ZACPT:139:6'
DTM+178:1608020718:201'
DTM+133:1607030700:201'
DTM+132:160702:101'
LOC+147+0121282::5'
MEA+WT++KGM:4200'
LOC+6+PTLEI'
LOC+12+ZADUR'
RFF+BM:1'
****EQD+CN+CXRU1123659+45R1+++4'****
NAD+CA+MACS:172:20'
UNT+2339+402'
UNZ+1+1'
The code I currently have is:
Imports System.IO
Imports System.Text.RegularExpressions
Imports System
Imports System.Collections
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sourceFilename1 As String
'Dim finalFile As List(Of String) = New List(Of String)
'Dim origFileData() As String = File.ReadAllText(sourceFilename1).Replace(vbCr, "").Replace(vbLf, "").Split({"'"}, StringSplitOptions.RemoveEmptyEntries)
OpenFileDialog1.Filter = "BAPLIE Files (*.*;*.*)|*.*;*.*"
If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
sourceFilename1 = OpenFileDialog1.FileName
End If
Dim TextFieldParser1 As New Microsoft.VisualBasic.FileIO.TextFieldParser(sourceFilename1)
TextFieldParser1.Delimiters = New String() {"'"}
TextFieldParser1.ReadLine.StartsWith("EQD+CN+")
'If sourceFilename1.StartsWith("EQD+CN+") Then
' numberString = sourceFilename1.Substring(sourceFilename1.IndexOf("CN+"), 14)
' txtLastName.Text = numberString.Substring(3)
'End If
While Not TextFieldParser1.EndOfData
Dim Row1 As String() = TextFieldParser1.ReadFields()
If DataGridView1.Columns.Count = 0 AndAlso Row1.Count > 0 Then
Dim i As Integer
For i = 0 To Row1.Count - 1
DataGridView1.Columns.Add("Column" & i + 1, "Column" & i + 1)
Next
End If
DataGridView1.Rows.Add(Row1)
End While
End Sub
End Class
I am not experienced at programming and doing this as a pet project.
I have re-written my code. I get my file to display the correct info on one line only, BUT now it only show ONE line in my datagrid if I run my program?
here is my new code:
Imports System.IO
Imports System.Text.RegularExpressions
Imports System
Imports System.Collections
Public Class Form1
'------THIS IS GOOD
Private Sub btnRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRun.Click
Dim sourceFilename2 As String = "*.edi | *.txt"
If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
sourceFilename2 = OpenFileDialog1.FileName
End If
Dim strm As IO.Stream = IO.File.OpenRead(sourceFilename2)
Dim sr As New IO.StreamReader(strm)
Dim sw = System.Diagnostics.Stopwatch.StartNew()
Dim line1 As String = ""
Dim trimchars() As Char = {"+", "'"}
grdMydata.Columns.Add("Column1", "POD") ' ------------------------- INDEX 0
grdMydata.Columns.Add("Column2", "BAY") ' ------------------------- INDEX 1
grdMydata.Columns.Add("Column3", "SLOT") ' ------------------------ INDEX 2
grdMydata.Columns.Add("Column4", "VGM WEIGHT") ' ------------------ INDEX 3
grdMydata.Columns.Add("Column5", "WT WEIGHT") ' ------------------- INDEX 4
grdMydata.Columns.Add("Column6", "CONTAINER ID") ' ---------------- INDEX 5
grdMydata.Columns.Add("Column7", "ISO CODE") ' -------------------- INDEX 6
grdMydata.Columns.Add("Column8", "FULL/EMPTY") ' ------------------ INDEX 7
grdMydata.Columns.Add("Column9", "CARRIER") ' --------------------- INDEX 8
Do While sr.Peek() <> -1
Dim Newline As String
Newline = System.Environment.NewLine
line1 = sr.ReadLine()
'-----------------The file info in the text box
'txtTopRows.Text = UNH+402+ & BAPLIE:1:911:UN:SMDG15' BAPLIE VERSION
If line1.Contains("SMDG15") Then
txtTopRows.Text = "BAPLIE ver 1.5 "
End If
If line1.Contains("SMDG20") Then
txtTopRows.Text = "BAPLIE ver 2.0 "
End If
If line1.Contains("SMDG22") Then
txtTopRows.Text = "BAPLIE ver 2.0 "
End If
'DTM+137:2016080408 50:301'
If line1.Contains("DTM+137") Then
txtTopRows.Text = txtTopRows.Text & Newline & "File Date : " & (line1.Substring(8, 10))
End If
'Port of load here
If line1.Contains("LOC+5") Then
txtTopRows.Text = txtTopRows.Text & Newline & "Port of Load : " & (line1.Substring(6, 5))
End If
'Port of Discharge here
If line1.Contains("LOC+61") Then
txtTopRows.Text = txtTopRows.Text & Newline & "Port of Disharge : " & (line1.Substring(7, 5))
End If
'-----------------------------------------------------------------------------------------
Dim row1 As Integer = Me.grdMydata.Rows.Add()
'grdMydata.Rows.Clear()
'''''Code to get all data on ONE row
row1 = grdMydata.CurrentCell.RowIndex
If line1.TrimStart(trimchars).StartsWith("LOC+147") Then
grdMydata.Rows(row1).Cells(1).Value = (line1.Substring(8, 3))
grdMydata.Rows(row1).Cells(2).Value = (line1.Substring(8, 7))
End If
If line1.TrimStart(trimchars).StartsWith("MEA+VGM") Then
grdMydata.Rows(row1).Cells(3).Value = (line1.Substring(13, 5))
End If
If line1.TrimStart(trimchars).StartsWith("MEA+WT") Then
grdMydata.Rows(row1).Cells(4).Value = (line1.Substring(12, 5))
End If
If line1.TrimStart(trimchars).StartsWith("EQD") Then
grdMydata.Rows(row1).Cells(5).Value = (line1.Substring(7, 11))
grdMydata.Rows(row1).Cells(6).Value = (line1.Substring(19, 4))
End If
If line1.TrimStart(trimchars).StartsWith("NAD+CA") Then
grdMydata.Rows.Item(row1).Cells(8).Value = (line1.Substring(7, 3))
End If
Dim blank As Boolean = True
For Each _row As DataGridViewRow In grdMydata.Rows
blank = True
For i As Integer = 0 To _row.Cells.Count - 1
If _row.Cells(i).Value IsNot Nothing AndAlso _row.Cells(i).Value <> "" Then
blank = False
Exit For
End If
Next
If blank Then
If Not _row.IsNewRow Then
grdMydata.Rows.Remove(_row)
End If
End If
Next
Loop
sr.Close()
sourceFilename2 = Nothing
sw.Stop()
txtDisplay1.Text = String.Format("File loaded in: {0} miliseconds" _
& vbCrLf & "Number of Containers: {1}", sw.ElapsedMilliseconds, grdMydata.Rows.Count)
'MsgBox ("Hai" & vbCrLf & "Welcome")
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Dim sourceFilename1 As String
Dim sw = System.Diagnostics.Stopwatch.StartNew()
sourceFilename1 = Nothing
sw.Stop()
Me.Close()
End Sub
End Class
If none of the values in the file contain + or ', then you can use the Split function:
Dim text = File.ReadAllText(sourceFilename1)
Dim lines = Split(text, "'")
For Each line in lines
Dim values = Split(line, "+")
DataGridView1.Rows.Add(values)
Next

How to generate all combinations of partitioning a string in VB.Net

Given a string, how do you generate all partitions of it (shown as smaller strings separated by commas)?
Also, what is the total number of partitions for a string of length n?
The following will give the result, but is not good on long strings.
String: CODE
C,O,D,E
C,O,DE
C,OD,E
C,ODE
CO,D,E
CO,DE
COD,E
String: PEACE
P,E,A,C,E
P,E,A,CE
P,E,AC,E
P,E,ACE
P,EA,C,E
P,EA,CE
P,EAC,E
PE,A,C,E
PE,A,CE
PE,AC,E
PE,ACE
PEA,C,E
PEA,CE
Sub getAllComb()
oriStr = TextBox1.Text
Dim tmp = ""
Dim k = 0
For i = 0 To oriStr.Length
For j = 1 To 3
'tmp = Mid(oriStr, i, j)
Try
tmp1(k) = oriStr.Substring(i, j)
k = k + 1
'tmp = oriStr.Substring(i, j)
'Debug.Print(tmp)
Catch ex As Exception
'Debug.Print("Error>>>>" + ex.Message)
Exit For
End Try
Next
Next
tmp = ""
For i = 0 To k
Debug.Print(i.ToString + "<i " + tmp1(i))
tmp = tmp & tmp1(i) & vbCrLf
Next
'MessageBox.Show(tmp)
Dim tmpAll1 = ""
tmpAll1 = addFunclen4(k)
MessageBox.Show(tmpAll1)
Debug.Print(tmpAll1)
TextBox1.Text = oriStr & vbCrLf & vbCrLf & tmpAll1
End Sub
Function addFunclen4(k As Integer) As String
Dim retVal = ""
Dim tmp = ""
Dim tmpAll = ""
Dim tmpStr = ""
Dim tmpAll1 = ""
For i = 0 To k
For i1 = 0 To k
For i2 = 0 To k
For i3 = 0 To k
For i4 = 0 To k
tmp = Form1.tmp1(i) + Form1.tmp1(i1) + Form1.tmp1(i2) + Form1.tmp1(i3) + Form1.tmp1(i4)
If Form1.tmp1(i) <> "" Then
If tmp = Form1.oriStr Then
tmpStr = Form1.tmp1(i) + "," + Form1.tmp1(i1) + "," + Form1.tmp1(i2) + "," + Form1.tmp1(i3) + "," + Form1.tmp1(i4)
Do While tmpStr.Contains(",,") = True
tmpStr = Replace(tmpStr, ",,", ",")
Loop
If Mid(tmpStr, tmpStr.Length, 1) = "," Then
tmpStr = Mid(tmpStr, 1, tmpStr.Length - 1)
End If
If tmpAll1.Contains(tmpStr) = False Then
tmpAll1 = tmpAll1 + tmpStr + vbCrLf
End If
End If
End If
Next
Next
Next
Next
Next
retVal = tmpAll1
Return retVal
End Function
I reckon [2^(n-1) - 1] in total:
(n-1) positions to put a comma, 2 "states" (comma or not comma), -1 for the trivial case with no commas.
A simpler algorithm would be to iterate through the number of cases and use the binary representation to determine whether to put a comma in each position.
For example (simple form with TextBox, Button and ListBox):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
Dim s As String = TextBox1.Text
If s.Length < 2 Then
MessageBox.Show("Enter a longer string")
Return
End If
For i = 1 To Math.Pow(2, s.Length - 1) - 1
Dim result As String = s(0)
For j = 1 To s.Length - 1
result = result & CommaOrNot(i, j) & s(j)
Next
ListBox1.Items.Add(result)
Next
End Sub
Private Function CommaOrNot(i As Integer, j As Integer) As String
If (i And Math.Pow(2, j - 1)) = Math.Pow(2, j - 1) Then
Return ","
Else
Return ""
End If
End Function
I really liked Fruitbat's approach. Here's an alternate version using a slightly different mechanism for the representation of the binary number and how to determine if the comma should be included or not:
Public Class Form1
Private combinations As List(Of String)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim s As String = TextBox1.Text
If s.Length < 2 Then
MessageBox.Show("Enter a longer string")
Exit Sub
End If
Button1.Enabled = False
ListBox1.DataSource = Nothing
ListBox1.Items.Clear()
ListBox1.Items.Add("Generating combinations...")
BackgroundWorker1.RunWorkerAsync(s)
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim s As String = e.Argument
Dim combinations As New List(Of String)
Dim binary() As Char
Dim values() As Char = s.ToCharArray
Dim max As Integer = Convert.ToInt32(New String("1", s.Length - 1), 2)
Dim sb As New System.Text.StringBuilder
For i As Integer = 0 To max
sb.Clear()
binary = Convert.ToString(i, 2).PadLeft(values.Length, "0").ToCharArray
For j As Integer = 0 To values.Length - 1
sb.Append(If(binary(j) = "0", "", ","))
sb.Append(values(j))
Next
combinations.Add(sb.ToString)
Next
e.Result = combinations
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
combinations = e.Result
ListBox1.Items.Clear()
ListBox1.Items.Add("Generating combinations...Done!")
ListBox1.Items.Add("Adding Results...one moment please!")
Application.DoEvents()
ListBox1.DataSource = Nothing
ListBox1.DataSource = combinations
Button1.Enabled = True
MessageBox.Show("Done!")
End Sub
End Class

vb.net Get PrivateMemorySize64 and process id sort by memory size

I've got the following:
Dim plist() As Process = Process.GetProcesses()
For Each prs As Process In plist
ListBox1.Items.Add(prs.ProcessName + " (" + (prs.PrivateMemorySize64 / 1024000).ToString() + " MB)")
But id really like to get it to list it by memory size if possible? If anyone has any ideas it would be much appreciated
Here is a basic sample, you will have to customise it to your needs.
Public Class Form1
'
Dim pList() As Process = Nothing
'
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'
Dim pItem As Process = Nothing
Dim pCounter As Integer = Nothing
'
pList = Process.GetProcesses()
For pCounter = 0 To pList.Count - 1
pItem = pList(pCounter)
ListBox1.Items.Add(pItem.ProcessName + " (" + (pItem.PrivateMemorySize64 / 1024000).ToString() + " MB)") '
Next
'sort list
SortProcessList()
'
End Sub
'
Sub SortProcessList()
'
Dim i As Integer
Dim j As Integer
Dim pTmp As Process
'
'sort list based on lowest usage first
For i = 0 To pList.Count - 2
For j = i + 1 To pList.Count - 1
If pList(i).PrivateMemorySize64 > pList(j).PrivateMemorySize64 Then
pTmp = pList(i)
pList(i) = pList(j)
pList(j) = pTmp
End If
Next
Next
ReloadSortedList()
'
End Sub
Sub ReloadSortedList()
'
Dim pItem As Process = Nothing
Dim pCounter As Integer = Nothing
'
ListBox1.Items.Clear()
For pCounter = 0 To pList.Count - 1
pItem = pList(pCounter)
ListBox1.Items.Add(pItem.ProcessName + " (" + (pItem.PrivateMemorySize64 / 1024000).ToString() + " MB)") '
Next
'tidy up
pItem = Nothing
pCounter = Nothing
'
End Sub
End Class

vb.net - Why do I get this error when trying to bubble sort a csv file?

I have a csv file which I'm trying to sort by data (numerical form)
The csv file:
date, name, phone number, instructor name
1308290930,jim,041231232,sushi
123123423,jeremy,12312312,albert
The error I get is: Conversion from string "jeremy" to type 'double'is not valid
Even though no where in my code I mention double...
My code:
Public Class Form2
Dim currentRow As String()
Dim count As Integer
Dim one As Integer
Dim two As Integer
Dim three As Integer
Dim four As Integer
'concatenation / and operator
'casting
Dim catchit(100) As String
Dim count2 As Integer
Dim arrayone(4) As Decimal
Dim arraytwo(4) As String
Dim arraythree(4) As Decimal
Dim arrayfour(4) As String
Dim array(4) As String
Dim bigstring As String
Dim builder As Integer
Dim twodata As Integer
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("D:\completerecord.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
Dim count As Integer
Dim currentField As String
count = 0
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
For Each currentField In currentRow
' makes one array to contain a record for each peice of text in the file
'MsgBox(currentField) '- test of Field Data
' builds a big string with new line-breaks for each line in the file
bigstring = bigstring & currentField + Environment.NewLine
'build two arrays for the two columns of data
If (count Mod 2 = 1) Then
arraytwo(two) = currentField
two = two + 1
'MsgBox(currentField)
ElseIf (count Mod 2 = 0) Then
arrayone(one) = currentField
one = one + 1
ElseIf (count Mod 2 = 2) Then
arraythree(three) = currentField
three = three + 1
ElseIf (count Mod 2 = 3) Then
arrayfour(four) = currentField
four = four + 1
End If
count = count + 1
'MsgBox(count)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Error Occured, Please contact Admin.")
End Try
End While
End Using
RichTextBox1.Text = bigstring
' MsgBox("test")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim NoMoreSwaps As Boolean
Dim counter As Integer
Dim Temp As Integer
Dim Temp2 As String
Dim listcount As Integer
Dim builder As Integer
Dim bigString2 As String = ""
listcount = UBound(arraytwo)
'MsgBox(listcount)
builder = 0
'bigString2 = ""
counter = 0
Try
'this should sort the arrays using a Bubble Sort
Do Until NoMoreSwaps = True
NoMoreSwaps = True
For counter = 0 To (listcount - 1)
If arraytwo(counter) > arraytwo(counter + 1) Then
NoMoreSwaps = False
If arraytwo(counter + 1) > 0 Then
Temp = arraytwo(counter)
Temp2 = arrayone(counter)
arraytwo(counter) = arraytwo(counter + 1)
arrayone(counter) = arrayone(counter + 1)
arraytwo(counter + 1) = Temp
arrayone(counter + 1) = Temp2
End If
End If
Next
If listcount > -1 Then
listcount = listcount - 1
End If
Loop
'now we need to output arrays to the richtextbox first we will build a new string
'and we can save it to a new sorted file
Dim FILE_NAME As String = "D:\sorted.txt"
'Location of file^ that the new data will be saved to
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
'If D:\sorted.txt exists then enable it to be written to
While builder < listcount
bigString2 = bigString2 & arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine
objWriter.Write(arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine)
builder = builder + 1
End While
RichTextBox2.Text = bigString2
objWriter.Close()
MsgBox("Text written to log file")
Else
MsgBox("File Does Not Exist")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
I think in this line is the problem
arrayone(one) = currentField
Here it trys to cast the string to a double. You have to use something like this:
arrayone(one) = Double.Parse(currentField)
or to have it a saver way:
Dim dbl As Double
If Double.TryParse(currentField, dbl) Then
arrayone(one) = dbl
Else
arrayone(one) = 0.0
End If