Binary Reader and allowed characters - vb.net

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

Related

How to browse from bottom to top of a text file in 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.

Data type long can not be converted

I have a problem with error which show me problem with long data type in this part of code:
If Not filename Then
Call Form15.Show()
TextBox1.Clear()
here is full code:
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim filename As String
Dim regCis = TextBox1.Text
filename = TextBox1.Text
Dim zakazCis As Double
Dim found As Boolean = False
found = True
If (Double.TryParse(TextBox2.Text, zakazCis)) Then
zakazCis = TextBox2.Text
Else
zakazCis = Nothing
End If
Dim basePath As String = "C:\_Montix a.s. - cloud\iMontix\Testy"
Dim filePath As String = IO.Path.Combine(basePath, filename & ".lbe")
'Napojeni tabulky
Dim table As DataTable = SdfDataSet.Tables("List1")
Me.Refresh()
'Vytvoreni dotazu
Dim expression As String
expression = ("[Čísla dílů] = '" & regCis & "'")
Dim foundRows() As DataRow
Me.PictureBox1.Invalidate()
Dim bla = "Label10"
'vykonani dotazu
foundRows = table.Select(expression)
If Not filename Then
Call Form15.Show()
TextBox1.Clear()
Else
If (foundRows(0)(2) = zakazCis) Then
'souhlasí regCis a zakcis
PictureBox1.Image = Image.FromFile("C:\_Montix a.s. - cloud\Visual Studio 2015\Projects\WindowsApplication17\WindowsApplication17\img\tick.png")
Label10.BackColor = Color.Green
Me.Controls(bla).Text = "SPRÁVNĚ"
fileprint.PrintThisfile(filePath)
Threading.Thread.Sleep(4000)
SendKeys.Send("{ENTER}")
TextBox2.Clear()
TextBox2.Select()
Button6.Hide()
PictureBox1.Hide()
Label10.Hide()
Else
'NEsouhlasí regCis a zakcis
PictureBox1.Image = Image.FromFile("C:\_Montix a.s. - cloud\Visual Studio 2015\Projects\WindowsApplication17\WindowsApplication17\img\cross.png")
Label10.BackColor = Color.Red
Form15.Show()
TextBox2.Clear()
TextBox2.Select()
End If
End If
End Sub
and here is code from form15
Public Class Form15
Private Sub Button11_Click(ByVal sender As Object, ByVal e As EventArgs)
Me.Hide()
End Sub
End Class
Do you known where is a problem?
You are using a string in a boolean expression. I guess, you might have added the string instead of the boolean by mistake. ('found' instead of 'filename')
If Not found Then
Call Form15.Show()
TextBox1.Clear()
Else

Need assistance with writing to a CSV file and saving entries

I am creating a student test score application which shows student averages, class averages (I haven't done this part yet) and can search for a particular student which shows up in the text boxes.
Can someone please tell me how to write the test scores and name of student entered into the text boxes to an Excel CSV file?
Also the save button keeps clearing all the enteries to the CSV file when I click on it. If anyone could tell me whats going on there, that would be great.
Imports System.IO
Public Class Form1
Structure Students
Dim StudentName As String
Dim Test1 As Double
Dim Test2 As Double
Dim Test3 As Double
Dim Test4 As Double
Dim Test5 As Double
End Structure
Dim StudentCounter As Integer = 0
Dim MyStudentArray(StudentCounter) As Students
Private Sub LoadDataFromFileToArray()
Dim TextFile As New System.IO.StreamReader(“..\..\StudentDataFile.csv”)
Dim strStudentData As String
strStudentData = TextFile.ReadLine()
Do Until strStudentData Is Nothing
lstAllStudentData.Items.Add(strStudentData)
WriteToArray(strStudentData)
strStudentData = TextFile.ReadLine()
Loop
TextFile.Close()
End Sub
Private Sub WriteToArray(ByVal CurrentLine)
Dim Values() As String = Split(CurrentLine, ",")
ReDim Preserve MyStudentArray(StudentCounter)
MyStudentArray(StudentCounter).StudentName = Values(0)
MyStudentArray(StudentCounter).Test1 = (Values(1))
MyStudentArray(StudentCounter).Test2 = (Values(2))
MyStudentArray(StudentCounter).Test3 = (Values(3))
MyStudentArray(StudentCounter).Test4 = (Values(4))
MyStudentArray(StudentCounter).Test5 = (Values(5))
StudentCounter += 1
End Sub
Private Sub btnAddStudent_Click(sender As Object, e As EventArgs) Handles btnAddStudent.Click
ReDim Preserve MyStudentArray(StudentCounter)
MyStudentArray(StudentCounter).Test1 = CDbl(txtTest1.Text)
MyStudentArray(StudentCounter).Test2 = CDbl(txtTest1.Text)
MyStudentArray(StudentCounter).Test3 = CDbl(txtTest1.Text)
MyStudentArray(StudentCounter).Test4 = CDbl(txtTest1.Text)
MyStudentArray(StudentCounter).Test5 = CDbl(txtTest1.Text)
MyStudentArray(StudentCounter).StudentName = (txtStudentName.Text)
StudentCounter += 1
End Sub
Private Sub CalculateIndividual()
Dim AverageScore As Double = 0
Dim Test1 As Double = CDbl(txtTest1.Text)
Dim Test2 As Double = CDbl(txtTest2.Text)
Dim Test3 As Double = CDbl(txtTest3.Text)
Dim Test4 As Double = CDbl(txtTest4.Text)
Dim Test5 As Double = CDbl(txtTest5.Text)
Dim AverageGrade As String
AverageScore = (Test1 + Test2 + Test3 + Test4 + Test5) / 5
lblScoreOutput.Text = AverageScore
lblScoreOutput.Visible = True
Select Case AverageScore
Case > 90
AverageGrade = "A+"
Case 80 To 90
AverageGrade = "A"
Case 70 To 80
AverageGrade = "B"
Case 60 To 70
AverageGrade = "C"
Case 50 To 60
AverageGrade = "D"
Case 35 To 50
AverageGrade = "E"
Case Else
AverageGrade = "UG"
End Select
lblLetterOutput.Text = AverageGrade
lblLetterOutput.Visible = True
End Sub
Private Sub Form_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Dim response As MsgBoxResult
response = MsgBox("Do you want to close Student Calculator", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm")
If response = MsgBoxResult.Yes Then
Me.Dispose()
ElseIf response = MsgBoxResult.No Then
e.Cancel = True
Exit Sub
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Dim response As MsgBoxResult
response = MsgBox("Do you want to close Student Calculator?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm")
If response = MsgBoxResult.Yes Then
Me.Dispose()
ElseIf response = MsgBoxResult.No Then
Exit Sub
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstAllStudentData.Items.Clear()
LoadDataFromFileToArray()
lstAllStudentData.Items.Clear()
LoadDataFromFileToArray()
Dim MySource As New AutoCompleteStringCollection()
For StudentCounter = 0 To StudentCounter - 1
MySource.Add(MyStudentArray(StudentCounter).StudentName)
Next
With txtSearch
.AutoCompleteCustomSource = MySource
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
.AutoCompleteSource = AutoCompleteSource.CustomSource
.Visible = True
Me.Controls.Add(txtSearch)
End With
End Sub
Private Sub lstAllStudentData_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstAllStudentData.SelectedIndexChanged
txtStudentName.Text = MyStudentArray(lstAllStudentData.SelectedIndex).StudentName
txtTest1.Text = MyStudentArray(lstAllStudentData.SelectedIndex).Test1
txtTest2.Text = MyStudentArray(lstAllStudentData.SelectedIndex).Test2
txtTest3.Text = MyStudentArray(lstAllStudentData.SelectedIndex).Test3
txtTest4.Text = MyStudentArray(lstAllStudentData.SelectedIndex).Test4
txtTest5.Text = MyStudentArray(lstAllStudentData.SelectedIndex).Test5
CalculateIndividual()
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim SearchField As String = txtSearch.Text
For StudentCounter = 0 To StudentCounter
If rdbStudent.Checked = True Then
If UCase(SearchField) = UCase(MyStudentArray(StudentCounter).StudentName) Then
lstAllStudentData.SelectedIndex = StudentCounter
Exit For
End If
End If
If rdbStudent.Checked = True Then
If UCase(SearchField) = UCase(MyStudentArray(StudentCounter).StudentName) Then
lstAllStudentData.SelectedIndex = StudentCounter
Exit For
End If
End If
Next
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim StudentFile As New System.IO.StreamWriter("..\..\StudentDataFile.csv")
For StudentCounter = 0 To MyStudentArray.Length - 1
StudentFile.Write(MyStudentArray(StudentCounter).StudentName)
StudentFile.Write(",")
StudentFile.Write(MyStudentArray(StudentCounter).Test1)
StudentFile.Write(",")
StudentFile.Write(MyStudentArray(StudentCounter).Test3)
StudentFile.Write(",")
StudentFile.Write(MyStudentArray(StudentCounter).Test4)
StudentFile.Write(",")
StudentFile.Write(MyStudentArray(StudentCounter).Test4)
StudentFile.Write(",")
StudentFile.WriteLine(MyStudentArray(StudentCounter).Test5)
Next
StudentFile.Close()
End Sub
End Class

How to change filepath when check a radiobutton? Visual basic

My problem here is that i have 3 radiobuttons for 3 different categories:
Huse Folii and Altele.
The idea is when i select a radiobutton,the filepath will change to Huse,Folii or Altele.
For example i tried to make _path :
Dim _path As String = IO.Path.Combine("C:\Descriere\Huse\")
then use the _path here:
Dim ioFile As New System.IO.StreamReader(_path + "a.txt")
but it didn't worked,for sure i do something wrong,but i can't find how or where to use that _path...
Here is the code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
On Error Resume Next
TextBox1.Clear()
If RadioButton1.Checked = True Then
Dim _path As String = IO.Path.Combine("C:\Descriere\Huse\")
End If
If RadioButton2.Checked = True Then
Dim _path As String = IO.Path.Combine("C:\Descriere\Folii\")
End If
If RadioButton3.Checked = True Then
IO.Path.
Dim _path As String = IO.Path.Combine("C:\Descriere\Altele\")
End If
Dim ioFile As New System.IO.StreamReader(_path + "a.txt")
Dim lines As New List(Of String)
Dim rnd As New Random()
Dim line As Integer
While ioFile.Peek <> -1
lines.Add(ioFile.ReadLine())
End While
line = rnd.Next(lines.Count + 1)
TextBox1.AppendText(lines(line).Trim())
ioFile.Close()
ioFile.Dispose()
Dim ioFile2 As New System.IO.StreamReader(path:=+"core.txt")
Dim lines2 As New List(Of String)
Dim rnd2 As New Random()
Dim line2 As Integer
While ioFile2.Peek <> -1
lines2.Add(ioFile2.ReadLine())
End While
line2 = rnd2.Next(lines2.Count + 1)
TextBox1.AppendText(lines2(line2).Trim())
ioFile2.Close()
ioFile2.Dispose()
Dim ioFile3 As New System.IO.StreamReader(path:=+"x.txt")
Dim lines3 As New List(Of String)
Dim rnd3 As New Random()
Dim line3 As Integer
While ioFile3.Peek <> -1
lines3.Add(ioFile3.ReadLine())
End While
line3 = rnd3.Next(lines3.Count + 1)
TextBox1.AppendText(lines3(line3).Trim())
ioFile3.Close()
ioFile3.Dispose()
TextBox1.Text = Replace(TextBox1.Text, "BRAND", TextBox2.Text)
TextBox1.Text = Replace(TextBox1.Text, "MODEL", TextBox3.Text)
Dim count As Integer = 0
count = TextBox1.Text.Split(" ").Length - 1
Label5.Text = "Caractere:" & Len(TextBox1.Text)
End Sub
You are using IO.Path.Combine but you have nothing to Combine at the place of use in your code. You have to use IO.Path.Combine later in your code because this is a method to Combine part of a path and a filename e.g. set your _path first and combine in a second step. Please note this code is not tested for your needs, because your coding is not clear to me.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim directoryName As String = "D:\"
On Error Resume Next
TextBox1.Clear()
If RadioButton1.Checked = True Then
directoryName = "D:\Descriere\Huse"
End If
If RadioButton2.Checked = True Then
directoryName = "D:\Descriere\Folii"
End If
If RadioButton3.Checked = True Then
'//--- IO.Path.
directoryName = "D:\Descriere\Altele"
End If
Dim ioFile As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "a.txt"))
...
Dim ioFile2 As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "core.txt"))
...
Dim ioFile3 As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "x.txt"))
...
End Sub
Please use the debugger of your IDE because your code isn't clean e.g. a hanging aroung IO.Path.

how to filter a datagridview when a database is not being used

I am able get the contents of a csv file to read into DataGridView1, but I am having trouble filtering the data from textbox2. I tried different things I have found online, but nothing has worked so far. this is what i have:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "C:\"
OpenFileDialog1.Filter = "CSV Files (*.csv)|*.csv"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
Me.TextBox1.Text = fName
GetData(fName, DataGridView1, True)
End Sub
Private Sub GetData(ByVal Path As String, ByRef DG As DataGridView, Optional ByVal NoHeader As Boolean = False)
Dim Fields() As String
Dim Start As Integer = 1
If NoHeader Then Start = 0
If Not File.Exists(Path) Then
Return
End If
Dim Lines() As String = File.ReadAllLines(Path)
Lines(0) = Lines(0).Replace(Chr(34), "")
Fields = Lines(0).Split(",")
If NoHeader Then
For I = 1 To Fields.Count - 1
Fields(I) = Str(I)
Next
End If
For Each Header As String In Fields
DG.Columns.Add(Header, Header)
Next
For I = Start To Lines.Count - 1
Lines(I) = Lines(I).Replace(Chr(34), "")
Fields = Lines(I).Split(",")
DG.Rows.Add(Fields)
Next
End Sub
I just want to be able to filter say column 5 (no column headers in csv file) by typing something in textbox2. Any help would be greatly appreciated. Thank you
Don't add the values to a DGV, but instead use a DataTable then just make a query on that. Example considers you have a combobox for some filter choices - they are other ways to get this to depending on your needs. This method requires you to have headers though.
Private dt As New DataTable
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "C:\"
OpenFileDialog1.Filter = "CSV Files (*.csv)|*.csv"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
Me.TextBox1.Text = fName
LoadData(fName)
FilterData(combobox1.Text, "some column name")
End Sub
Private Sub LoadData(ByVal Path As String)
Dim Fields() As String
Dim Start As Integer = 1
If NoHeader Then Start = 0
If Not File.Exists(Path) Then
Return
End If
Dim Lines() As String = File.ReadAllLines(Path)
Lines(0) = Lines(0).Replace(Chr(34), "")
Fields = Lines(0).Split(",")
For I = 1 To Fields.Count - 1
Fields(I) = Str(I)
Next
For Each Header As String In Fields
dt.Columns.Add(Header, Header)
Next
For I = Start To Lines.Count - 1
Lines(I) = Lines(I).Replace(Chr(34), "")
Fields = Lines(I).Split(",")
dt.Rows.Add(Fields)
Next
End Sub
Private Sub FilterData(filter As String, columnName as string)
Dim query = From dr As DataRow In dt.Rows Where dr(columnName).ToString = filter
DGV.DataSource = query
End Sub