How to browse from bottom to top of a text file in vb.net? - vb.net

I cannot get my code below to work correctly, in fact I want to press a back button in order to go up the lines one by one of a text file then I cut the chain into 3 parts.
Dim LinesOfText() As String = System.IO.File.ReadAllLines("c:\essai.librairie", Encoding.UTF8)
For line As Integer = LinesOfText.Length - 1 To 0 Step -1
Dim currentLine As String = LinesOfText(line)
Dim value As String = currentLine
Dim startIndex As Integer = 0
Dim length As Integer = 17
Dim substring As String = value.Substring(startIndex, length)
Dim subs As String = value.Substring(17, 90)
Dim subst As String = value.Substring(107, 120)
TextBox1.Text = substring
TextBox2.Text = subs
TextBox3.Text = subst
Next

If you store the lines and a line counter so that they are in scope where needed, you can do it like this:
Imports System.IO
Public Class Form1
Dim lines As String()
Dim currentLine As Integer = -1
Sub LoadData(filename As String)
lines = File.ReadAllLines(filename)
currentLine = lines.Length - 1
End Sub
Sub ShowCurrentLine()
If currentLine >= 0 Then
TextBox1.Text = lines(currentLine).Substring(0, 3)
TextBox2.Text = lines(currentLine).Substring(4, 3)
TextBox3.Text = lines(currentLine).Substring(8, 3)
lblLineNo.Text = (currentLine + 1) & "/" & lines.Length
Else
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
lblLineNo.Text = "-"
End If
End Sub
Private Sub bnNext_Click(sender As Object, e As EventArgs) Handles bnNext.Click
If currentLine < lines.Length - 1 Then
currentLine += 1
ShowCurrentLine()
End If
End Sub
Private Sub bnPrev_Click(sender As Object, e As EventArgs) Handles bnPrev.Click
If currentLine > 0 Then
currentLine -= 1
ShowCurrentLine()
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadData("C:\temp\SO67209265.txt")
ShowCurrentLine()
End Sub
End Class
You will need to set the substring parameters for your data—I just used a small text file—and the filename to be loaded.
The label lblLineNo is used to show the current line number, starting at 1.

Related

Exporting CSV from ListView in VB.NET

i am having a bit of issue with exporting my data from a List-view in VB.NET i have included screenshots of what i am seeing basically i want to see only the Values in my csv file when i export it,
as you can see i am seeing what the List-box is showing, those values are coming from the List View Before Export. also i need the export to be in 1 column not rows as shown
any help would be great..
''''
Imports System.IO
Imports System.IO.StreamReader
Imports System.IO.StreamWriter
Imports System.Data.DataSet
Public Class Form1
Private Sub startcol_Click(sender As Object, e As EventArgs) Handles startcol.Click
Timer1.Enabled = True
End Sub
Private Sub stopcol_Click(sender As Object, e As EventArgs) Handles stopcol.Click
Timer1.Enabled = False
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Const MIN As Double = 5.0
Const MAX As Double = 400.0
Const DEC_PLACES As Integer = 2
Dim rnd As New Random
Dim list As Integer()
'Generate a random number X where MIN <= X < MAX and then round to DEC_PLACES decimal places.
Dim dbl As Double = Math.Round(rnd.NextDouble() * (MAX - MIN) + MIN, DEC_PLACES)
weight.Text = dbl
Dim newItem As New ListViewItem(weight.Text)
newItem.SubItems.Add(weight.Text)
'newItem.SubItems.Add(TextBox3.Text)
ListBox1.Items.Add(newItem)
ListView1.Items.Add(newItem)
rowcnt.Text = ListView1.Items.Count
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' ExportDatasetToCsv(List)
'WriteToTextFile()
Me.DoSave()
End Sub
Private Sub DoSave()
Dim SFD As New SaveFileDialog()
Try
With SFD
.AddExtension = True
.CheckPathExists = True
.CreatePrompt = False
.OverwritePrompt = True
.ValidateNames = True
.ShowHelp = True
.DefaultExt = "txt"
.Filter = _
"CSV Files (*.csv)|*.csv|" & _
"All files|*.*"
.FilterIndex = 1
If .ShowDialog() = Windows.Forms.DialogResult.OK Then
Me.DoSaveItems(.FileName)
End If
End With
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, Me.Text)
End Try
End Sub
' save All values from ListView1
Private Sub DoSaveItems(ByVal fileName As String)
If fileName Is Nothing = False Then
If fileName.Length > 0 Then
Using writer As New System.IO.StreamWriter(fileName)
For Each currentItem As Object In Me.ListView1.Items
writer.Write(currentItem.ToString() & ",")
Next
End Using
End If
End If
End Sub
Public Function ExportListViewToCSV(ByVal filename As String, ByVal lv As ListView) As Boolean
Try
' Open output file
Dim os As New StreamWriter(filename)
' Write Headers
For i As Integer = 0 To lv.Columns.Count - 1
' replace quotes with double quotes if necessary
os.Write("""" & lv.Columns(i).Text.Replace("""", """""") & """,")
Next
os.WriteLine()
' Write records
For i As Integer = 0 To lv.Items.Count - 1
For j As Integer = 0 To lv.Columns.Count - 1
os.Write("""" & lv.Items(i).SubItems(j).Text.Replace("""", """""") + """,")
Next
os.WriteLine()
Next
os.Close()
Catch ex As Exception
' catch any errors
Return False
End Try
Return True
End Function
Public Sub TestExportToCSV()
Dim dlg As New SaveFileDialog
dlg.Filter = "CSV files (*.CSV)|*.csv"
dlg.FilterIndex = 1
dlg.RestoreDirectory = True
If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
If ExportListViewToCSV(dlg.FileName, ListView1) Then
Process.Start(dlg.FileName)
End If
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
'TestExportToCSV()
End Sub
End Class
''''
As you haven't shown us your code, we can't tell you how to modify it specifically. In general though, you can treat the ListView somewhat like a 2D array, looping through the rows and the columns to get the data. That means that you could output the data to a CSV like this:
Using writer As New StreamWriter(filePath)
For rowIndex = 0 To myListView.Items.Count - 1
Dim item = myListView.Items(rowIndex)
'Write a line break before all but the first line.
If rowIndex > 0 Then
writer.WriteLine()
End If
For columnIndex = 0 To myListView.Columns.Count - 1
Dim subItem = item.SubItems(columnIndex)
'Write a field delimiter before all but the first field.
If columnIndex > 0 Then
write.Write(",")
End If
writer.Write(subItem.Text)
Next
Next
End Using
That's the old-school way. There are more succinct options, especially with the advent of LINQ:
File.WriteAllLines(filePath,
myListView.Items.
Cast(Of ListViewItem)().
Select(Function(item) String.Join(",",
item.SubItems.
Cast(Of ListViewItem.ListViewSubItem)().
Select(Function(subItem) subItem.Text))))
EDIT:
If you want to include the column headers then you can modify the above code like so:
Using writer As New StreamWriter(filePath)
For columnIndex = 0 To myListView.Columns.Count - 1
Dim column = myListView.Columns(columnIndex)
'Write a field delimiter before all but the first field.
If columnIndex > 0 Then
writer.Write(",")
End If
writer.Write(column.Text)
Next
For rowIndex = 0 To myListView.Items.Count - 1
Dim item = myListView.Items(rowIndex)
'Write a line break before each line.
writer.WriteLine()
For columnIndex = 0 To myListView.Columns.Count - 1
Dim subItem = item.SubItems(columnIndex)
'Write a field delimiter before all but the first field.
If columnIndex > 0 Then
writer.Write(",")
End If
writer.Write(subItem.Text)
Next
Next
End Using
File.WriteAllLines(filePath,
myListView.Items.
Cast(Of ListViewItem)().
Select(Function(item) String.Join(",",
item.SubItems.
Cast(Of ListViewItem.ListViewSubItem)().
Select(Function(subItem) subItem.Text))).
Prepend(String.Join(",",
myListView.Columns.
Cast(Of ColumnHeader)().
Select(Function(header) header.Text))))

Score not being calculated correctly

Hi I'm created a program for a project and I've now started running some tests and the score for the user isn't being calculated correctly and I believe that it can't compare the answer given to the correct answer. I'm very confused and need any help that can be given. My code looks like this, any confusing parts and I'll try and explain.
Imports System.IO
Public Class QuestionScreen
Dim score As Integer = 0
Dim count As Integer
Dim Difficulty_ext As String
Dim questions, answers As New List(Of String)()
Private i As Integer
Sub ReadFile()
If Main.Diff_DDown.Text = "Easy" Then
Difficulty_ext = "questions - Easy"
ElseIf Main.Diff_DDown.Text = "Medium" Then
Difficulty_ext = "questions - Medium"
Else
Difficulty_ext = "questions - Difficult"
End If
Randomize()
Dim countline = File.ReadAllLines("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt").Length
Dim numline As Integer
Dim values() As String
Using sr As New StreamReader("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt")
While Not sr.EndOfStream
values = sr.ReadLine().Split(","c)
questions.Add(values(0))
answers.Add(values(1))
End While
End Using
numline = Int(Rnd() * countline)
For i As Integer = 0 To numline
Question.Text = questions(i)
Act_ANS.Text = answers(i)
Next
End Sub
Private Sub Pass_Btn_Click(sender As Object, e As EventArgs) Handles Pass_Btn.Click
If count < 10 Then
Call ReadFile()
count = count + 1
Ans_TxtBx.Text = ""
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
End If
End Sub
Public Sub Submit_Btn_Click(sender As Object, e As EventArgs) Handles Submit_Btn.Click
If count < 10 Then
Call ReadFile()
count = count + 1
If Ans_TxtBx.Text = answers(i) Then
score = score + 1
End If
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
count = 0
End If
Ans_TxtBx.Text = ""
End Sub
Private Sub QuestionScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ReadFile()
End Sub
End Class
OK..... Try this, I have debugged your code trying to leave it pretty much as you had it, there were a number of problems, nothing major just a few lines of code in the wrong place....
Imports System.IO
Public Class Form1
Dim score As Integer = 0
Dim count As Integer
Dim Difficulty_ext As String
Dim questions, answers As New List(Of String)()
Private i As Integer
Sub ReadFile()
If Diff_DDown.Text = "Easy" Then
Difficulty_ext = "questions - Easy"
ElseIf Diff_DDown.Text = "Medium" Then
Difficulty_ext = "questions - Medium"
Else
Difficulty_ext = "questions - Difficult"
End If
Randomize()
Try
Dim countline = File.ReadAllLines("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt").Length
Dim numline As Integer
Dim values() As String
' clear the list of questions and answers
answers.Clear()
questions.Clear()
'''''''''''''''''''''''''''''''''''''''''
Using sr As New StreamReader("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt")
While Not sr.EndOfStream
values = sr.ReadLine().Split(","c)
questions.Add(values(0))
answers.Add(values(1))
End While
End Using
numline = Int(Rnd() * countline)
For i = 0 To numline
Question.Text = questions(i)
Act_ANS.Text = answers(i)
Next
Catch ex As Exception
End Try
End Sub
Private Sub Pass_Btn_Click(sender As Object, e As EventArgs) Handles Pass_Btn.Click
If count < 10 Then
count = count + 1
Ans_TxtBx.Text = ""
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
End If
Call ReadFile() ' move this to the bottom
End Sub
Public Sub Submit_Btn_Click(sender As Object, e As EventArgs) Handles Submit_Btn.Click
If count < 10 Then
count = count + 1
If Ans_TxtBx.Text = answers(i - 1) Then ' need to subtract 1 here
score = score + 1
End If
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
count = 0
End If
Ans_TxtBx.Text = ""
Call ReadFile() ' move this to the bottom
End Sub
Private Sub QuestionScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ReadFile()
End Sub
End Class

looping to add 271 records into my dictionary it only add 150 then exit the subroutine. (VB.net 2015)

For VB.net 2015
I'm a new programmer. I've been warping my brain around this for 2 days. Can seem to see the problem. It seems I can only add 150 records to the dictionary. I'm not sure where its failing in the code. I'm not getting any errors or warnings.
Really hope someone can give me a hand.
Heres a link to my file I'm working with.
https://drive.google.com/file/d/0B1zf86jcRv49Y1lCMHRvNWt4UFk/view?usp=sharing
P.S. Sry about the crappy coding skill :-)
Imports System
Imports System.IO
Public Class Form1
Dim xx As Integer = 0
Private MainDataList As New Dictionary(Of String, List(Of String))
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim temp1 As List(Of String)
'MsgBox(xx)
If MainDataList.ContainsKey(TextBox1.Text) Then
temp1 = MainDataList.Item(TextBox1.Text)
Label1.Text = temp1(0)
Beep()
Else
Label1.Text = "Not Found"
Beep()
Beep()
End If
TextBox1.Text = ""
End Sub
Private Sub GetData()
Dim ReadDataLine(50000) As String
Try
' Open the file using a stream reader.
Using sr As New StreamReader("C:\Inventory\Invatory.csv")
'Dim line As String
' Read the stream to a string and write the string to the console.
ReadDataLine(0) = sr.ReadLine
Do While (sr.EndOfStream = False)
ReadDataLine(xx) = sr.ReadLine
'AddToList(ReadDataLine) ' pars data into main list
'MsgBox(sr.ReadLine)
xx = xx + 1
Loop
sr.Close()
'line = sr.ReadLine()
End Using
Catch e As Exception
'MsgBox(xx)
MsgBox("The file could not be read:")
MsgBox(e.Message)
End Try
'MsgBox(xx)
'xx = 0
For Each i As String In ReadDataLine
AddToList(i)
'MsgBox(xx)
'xx = xx + 1
Next
End Sub
Private Sub AddToList(data As String)
Dim barCode As String = ""
Dim steps As Integer = 1
Dim LastPos As Integer = 2
Dim datalist As New List(Of String)
Dim firstPass As Boolean = False
For i = 2 To Len(data)
'Find end of cell
If Mid(data, i, 1) = "," Then
If firstPass = False Then
barCode = Mid(data, LastPos, i - 2)
'MsgBox(Mid(data, LastPos, i - 2))
LastPos = i
firstPass = True
Else
Dim temp As Integer = i - LastPos
datalist.Add(Mid(data, LastPos + 1, temp - 1))
'MsgBox(Mid(data, LastPos + 1, temp - 1))
LastPos = i
End If
End If
Next
MainDataList.Add(barCode, datalist)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GetData()
Label1.Text = "Ready!"
Me.Show()
TextBox1.Focus()
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
End Class

How to make a program that would detect the same characters within two strings

so i made this but when i enter a string it would only detect one character
and it wont convert the entered string to lower case too
Dim readme, readme2 As String
Dim j, i As Integer
Dim Compare As Integer
readme = TextBox1.Text
readme2 = TextBox2.Text
readme.ToLower.Substring(i, readme.Length)
readme2.ToLower.Substring(j, readme2.Length)
For i = 0 To readme.Length
For j = 0 To readme2.Length
If readme = readme2 Then
Compare = +1
End If
Next
Next
Label4.Text = Compare`enter code here`
Strings are immutable. You cannot apply a method to a string and expects that string to change in response to the inner operations of that method.
You need to reassign the result of the operation to the same string that you have used to call the method
readme = readme.ToLower()
readme2 = readme2.ToLower()
The second part of your question is more confused, are you trying to count the number of equal chars in the same position?
In that case your loop should be
Dim maxLenToCheck = Math.Min(readme.Length, readme2.Length)
For i = 0 To maxLenToCheck - 1
If readme(i) = readme2(i) Then
Compare += 1
End If
Next
In that loop you set always the Compare to 1, the correct syntax to increment the Compare variable is
Compare += 1
Following your comment below, then I presume that your loop should be written as
Dim Compare = 0
For i = 0 To readme.Length - 1
for j = 0 to readme2.Length -1
If readme(i) = readme2(j) AndAlso _
Not Char.IsWhiteSpace(readme(i)) Then
Compare += 1
End If
Next
Next
Based on the comments in the solution by Steve, the author wants to know the count of letters occurring in both strings, ignoring case and white spaces.
By my count, however, the solution should be 21, not 20. Here is a solution using LINQ that also gives visual feedback on where those letters are located:
Public Class Form1
Private Class LetterCount
Public Letter As Char
Public Count As Integer
Public Overrides Function ToString() As String
Return Letter & " : " & Count
End Function
End Class
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "This is a Test"
TextBox2.Text = "This should be tryed before"
RichTextBox1.ReadOnly = True
RichTextBox1.Font = New Font("MS Courier", 14) ' monospaced font
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBox1.Text = TextBox1.Text & vbCrLf & TextBox2.Text & vbCrLf
Dim charsA As New List(Of Char)(TextBox1.Text.ToLower.ToCharArray.Where(Function(x) Not Char.IsWhiteSpace(x)))
Dim charsB As New List(Of Char)(TextBox2.Text.ToLower.ToCharArray.Where(Function(x) Not Char.IsWhiteSpace(x)))
Dim DistinctCommonLetters = (From A In charsA, B In charsB Where A = B Select A).Distinct
Dim DistinctCounts =
From Letter In DistinctCommonLetters, C In charsA.Concat(charsB)
Where C = Letter
Group By Letter Into Group
Select New LetterCount With {.Letter = Letter, .Count = Group.Count}
Dim TotalMatches = DistinctCounts.Sum(Function(x) x.Count)
ListBox1.DataSource = DistinctCounts.ToList
Label1.Text = "TotalMatches: " & TotalMatches
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim LC As LetterCount = ListBox1.SelectedItem
RichTextBox1.SelectAll()
RichTextBox1.SelectionColor = Color.Black
Dim index As Integer = RichTextBox1.Find(LC.Letter, 0, RichTextBoxFinds.None)
While index <> -1
RichTextBox1.Select(index, 1)
RichTextBox1.SelectionColor = Color.Red
index = RichTextBox1.Find(LC.Letter, index + 1, RichTextBoxFinds.None)
End While
End Sub
End Class

Binary Reader and allowed characters

I have a problem.
Now program working like this:
Reading binary file bytes. &H1E and &H1F Allowed characters only :A123456789
If in file is B or C or D or E or F....... textbox1 = bad file
That's working. Now I want to add verification in &H10.
Allowed characters only 26
If other characters textbox1 = bad file
Imports System.IO
Imports System.IO.SeekOrigin
Public Class Form1
Dim charactersAllowed As String = "A123456789"
Dim swap As String = "26"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OFD As New OpenFileDialog
Dim fullFile() As Byte
With OFD
.Filter = "Binary files (*.bin)|*.bin"
End With
If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
fullFile = File.ReadAllBytes(OFD.FileName)
TextBox1.AppendText(fullFile(&H1E).ToString("X2") & " ")
TextBox1.AppendText(fullFile(&H1F).ToString("X2"))
TextBox4.AppendText(fullFile(&H10).ToString("X2"))
End If
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim theText As String = TextBox1.Text
Dim Letter As String
Dim SelectionIndex As Integer = TextBox1.SelectionStart
Dim Change As Integer
For x As Integer = 0 To TextBox1.Text.Length - 1
Letter = TextBox1.Text.Substring(x, 1)
If charactersAllowed.Contains(Letter) = False Then
theText = theText.Replace(Letter, String.Empty)
Change = 1
End If
Next
TextBox1.Text = theText
TextBox1.Select(SelectionIndex - Change, 0)
End Sub
Private Sub TextBox4_TextChanged(sender As Object, e As EventArgs) Handles TextBox4.TextAlignChanged
Dim check As String = TextBox4.Text
Dim check2 As String
Dim check3 As Integer = TextBox4.SelectionStart
Dim check4 As Integer
For x As Integer = 0 To TextBox4.Text.Length - 1
check2 = TextBox4.Text.Substring(x, 1)
If swap.Contains(check2) = False Then
check = check.Replace(check2, String.Empty)
check4 = 1
End If
Next
TextBox1.Text = check
TextBox1.Select(check3 - check4, 0)
End Sub
Hard to decode, but an obvious approach is to prevent editing when the byte has the wrong value:
If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
fullFile = File.ReadAllBytes(OFD.FileName)
If fullFile(&H10) <> 26 Then
TextBox1.Text = "Bad file"
TextBox1.Enabled = False
TextBox4.Enabled = False
Else
TextBox1.Enabled = True
TextBox4.Enabled = True
'' etc...
End If
End If