reading bits with for loop, I get 7 bits instead of 8, what's the wrong with this code - vb.net

OutPuts:
TextBox 2 : FalseTrueTrueTrueTrueTrueFalseFalse
TextBox 3 : 1111100
My problem is why is that the first boolean of "TextBox 2" is "False" and the first integer of "TextBox 3" is 1 ? "TextBox 2" has 8 booleans while "TextBox 3" only has 7 bits. And apparently, in "TextBox 3, the first bit is not there. Where have I done wrong .. ? commentary has provided in the code. Please shed some light here.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim array() As Byte = File.ReadAllBytes("D:\binfile.bin")
Using memory As MemoryStream = New MemoryStream(array)
Using reader As BinaryReader = New BinaryReader(memory)
ba1 = New BitArray(array)
Dim bit_set As Integer
For i As Integer = 0 To 7
'to view all 8 bits in boolean format
TextBox2.Text = TextBox2.Text & ba1.Get(i)
If ba1.Get(i) = False Then
boolean2bits = 0
'End If
ElseIf ba1.Get(i) = True Then
boolean2bits = 1
End If
'to collect all 8 bits in integer format
bit_set = bit_set & boolean2bits
If (i = 7) Then
Exit For
End If
Next
'to view collected bits in the text box
TextBox3.Text = bit_set
End Using
End Using
End Sub

Simply because you are assigning the value 01111100 to the integer variable bit_set. But of course, as an integer, that leading 0 is not significant, so it gets stripped out automatically, and gets simplified to simply 1111100, because it is the same number after all.
If you don't want to lose the leading zero for display purposes, then you probably don't want bit_set to be of type Integer. Just declare at as a Dim bit_set As String, and the leading zero will not disappear.

Looks like you're making some progress towards your end goal Pretty_Girl.
Here are some snippets to take in and digest:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
ba1 = New BitArray(File.ReadAllBytes("D:\binfile.bin"))
Dim bits As New List(Of String)
Dim bools As New List(Of String)
For i As Integer = 0 To 7
bools.Add(ba1.Get(i).ToString)
bits.Add(If(ba1.Get(i), "1", "0"))
Next
'to view collected bits/bools in the text box
TextBox2.Text = String.Join(",", bools.ToArray)
TextBox3.Text = String.Join("", bits.ToArray)
End Sub
Alternate Version 2:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
ba1 = New BitArray(File.ReadAllBytes("D:\binfile.bin"))
TextBox2.Clear()
TextBox3.Clear()
For i As Integer = 0 To 7
TextBox2.AppendText(ba1.Get(i).ToString & ",")
TextBox3.AppendText(If(ba1.Get(i), "1", "0"))
Next
End Sub
Alternate Version 3:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
ba1 = New BitArray(File.ReadAllBytes("D:\binfile.bin"))
Dim bits As New System.Text.StringBuilder
Dim bools As New System.Text.StringBuilder
For i As Integer = 0 To 7
bools.Append(ba1.Get(i).ToString & ",")
bits.Append(If(ba1.Get(i), "1", "0"))
Next
TextBox2.Text = bools.ToString
TextBox3.Text = bits.ToString
End Sub

Related

How can I get ten numbers and displays the biggest and lowest one?

sorry I'm a newbie and I'm trying to write a program to get ten integers from user with a an Inputbox or Textbox and displays the biggest and lowest one in a label with visual basic. I'll be appreciated if you help me out with this.
Thank you. this is my solution. I don't know how to compare these ten numbers with each other.
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim i, Container, Max, Numbers
Max = 0
i = 1
While (i <= 10)
Numbers = InputBox("please enter a number", "Enter a number")
Max = Numbers
Container = Container & " " & Numbers
i = i + 1
End While
lblresult.Text = Container
End Sub
conceptually speaking you should use a List(Of Integer) or List(Of Double), perform the loop 10 times adding the value into the list.
Suppose this is our list
Dim container As New List(Of Integer)
To get input
Dim userInput = ""
Dim input As Integer
userInput = InputBox("please enter a number", "Enter a number")
If Integer.TryParse(userInput, input) Then
container.Add(input)
End If
After the loop
Console.WriteLine($"Min: {container.Min()} Max: {container.Max()}")
Does this make sense to you ?
Edit, based on asking for Windows Forms example.
You could do the following instead of a InputBox, requires a label, a button and a TextBox.
Public Class MainForm
Private container As New List(Of Integer)
Private Sub CurrentInputTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) _
Handles CurrentInputTextBox.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
CurrentLabel.Text = "Enter number 1"
End Sub
Private Sub ContinueButton_Click(sender As Object, e As EventArgs) _
Handles ContinueButton.Click
If Not String.IsNullOrWhiteSpace(CurrentInputTextBox.Text) Then
container.Add(CInt(CurrentInputTextBox.Text))
CurrentLabel.Text = $"Enter number {container.Count + 1}"
If container.Count = 10 Then
ContinueButton.Enabled = False
CurrentLabel.Text =
$"Count: {container.Count} " &
$"Max: {container.Max()} " &
$"Min: {container.Min()}"
Else
ActiveControl = CurrentInputTextBox
CurrentInputTextBox.Text = ""
End If
End If
End Sub
End Class
I really didn't want to do your homework for you but I was afraid you might be hopelesly confused.
First let's go over your code. See comments
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim i, Container, Max, Numbers 'Don't declare variables without an As clause
Max = 0 'Max is an object
i = 1 'i is and object
While i <= 10 'the parenthesis are unnecessary. You can't use <= 2 with an object
Numbers = InputBox("please enter a number", "Enter a number")
Max = Numbers
Container = Container & " " & Numbers 'Container is an object; you can't use & with an object
i = i + 1 'Again with the object i can't use +
End While
lblresult.Text = Container
End Sub
Now my approach.
I created a List(Of T) at the Form level so it can be seen from different procedures. The T stands for type. I could be a built in type or type you create by creating a Class.
The first click event fills the list with the inputted numbers. I used .TryParse to test if the input is a correct value. The first parameter is a string; the input from the user. The second parameter is a variable to hold the converted string. .TryParse is very clever. It returns True or False base on whether the input string can be converted to the correct type and it fills the second parameter with the converted value.
The second click event loops through the list building a string to display in Label1. Then we use methods available to List(Of T) to get the numbers you desire.
Private NumbersList As New List(Of Integer)
Private Sub FillNumberList_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i As Integer
While i < 10
Dim input = InputBox("Please enter a whole number")
Dim inputInt As Integer
If Integer.TryParse(input, inputInt) Then
NumbersList.Add(inputInt)
i += 1 'We only increment i if the parse is succesful
End If
End While
MessageBox.Show("Finished Input")
End Sub
Private Sub DisplayResults_Click(sender As Object, e As EventArgs) Handles Button2.Click
Label1.Text = "You input these numbers "
For Each num In NumbersList
Label1.Text &= $"{num}, "
Next
Label2.Text = $"The largest number is {NumbersList.Max}"
Label3.Text = $"The smallest number is {NumbersList.Min}"
End Sub

How to randomize a quiz on vbnet

I'm new at visual basic programming and everything was fine until our topic shifted to arrays. I tried to understand it's code using Java. (Example: method are called functions.. .)
My prof has given us an exercise to create a Quiz program that asks the user more than 5 questions (in textbox) with choices (in buttons) and computes the score at the end (All just in one form). If the user click an a button it will tell if it's right or wrong and then proceed to change the question along with the choices.
*Required: - After the user finish the quiz the score will be displayed and there should be a restart button and all the question will be asked again randomly no pattern. - Try to make functions.
I tried searching the web since yesterday and I still have made no progress at my code.
Public Class Form1
Dim questions(5) As String
Dim answers(5) As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Method/Function for loading the Q&A
loadQsAndAs()
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Me.Close()
End Sub
Private Sub loadQsAndAs()
'Questions
questions(0) = "What is 1 + 1?"
questions(1) = "Who is the first man to walk on the Moon?"
questions(2) = "What is the name of the main character in the movie: Yes Man! (2007)"
questions(3) = "If I gave you three apples and you ate two, how many is left?"
questions(4) = "What do you want in your final grade?"
questions(5) = "What is the name of the thing(s) that you use whenever you eat?"
'Answers
answers(0) = "2"
answers(1) = "Neil Armstrong"
answers(2) = "Jim Carrey"
answers(3) = "1"
answers(4) = "A 4.0"
answers(5) = "A Spoon and Fork"
TextBox1.Text = setTheQuestion()
Button1.Text = setTheAnswer1()
Button2.Text = setTheAnswer2()
Button3.Text = setTheAnswer3()
Button4.Text = setTheAnswer4()
End Sub
Private Function setTheQuestion() As String
Dim randomValue As New Random
Dim randomQ As String = ""
Dim i As Integer
Dim index As Integer
For i = 0 To 0
index = randomValue.Next(0, questions.Length)
randomQ &= questions(index)
Next
Return randomQ
End Function
Private Function setTheAnswer1() As String
Dim randomValue As New Random
Dim randomAns As String = ""
Dim i As Integer
Dim index As Integer
For i = 0 To 0
index = randomValue.Next(0, answers.Length)
randomAns &= answers(index)
Next
Return randomAns
End Function
Private Function setTheAnswer2() As String
Dim randomValue As New Random
Dim randomAns As String = ""
Dim i As Integer
Dim index As Integer
For i = 0 To 0
index = randomValue.Next(1, answers.Length)
randomAns &= answers(index)
Next
Return randomAns
End Function
Private Function setTheAnswer3() As String
Dim randomValue As New Random
Dim randomAns As String = ""
Dim i As Integer
Dim index As Integer
For i = 0 To 0
index = randomValue.Next(2, answers.Length)
randomAns &= answers(index)
Next
Return randomAns
End Function
Private Function setTheAnswer4() As String
Dim randomValue As New Random
Dim randomAns As String = ""
Dim i As Integer
Dim index As Integer
For i = 0 To 0
index = randomValue.Next(3, answers.Length)
randomAns &= answers(index)
Next
Return randomAns
End Function
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
loadQsAndAs()
End Sub
End Class
Public Class Form1
Dim questions As New ArrayList
Dim answers As New ArrayList
Dim dtQAMain As New DataTable
Dim questionsCopy As New ArrayList
Dim alAnsButton As New ArrayList 'arraylist to store all answer button.
Dim totalScore As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
'Method/Function for loading the Q&A
alAnsButton.Add(Button1)
alAnsButton.Add(Button2)
alAnsButton.Add(Button3)
alAnsButton.Add(Button4)
loaddtQA()
loadQsAndAs()
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button5.Click
Me.Close()
End Sub
Private Sub loaddtQA()
dtQAMain = New DataTable
dtQAMain.Columns.Add("Q")
dtQAMain.Columns.Add("A")
For i = 0 To 5
questions.Add("")
answers.Add("")
Next
'Questions
questions(0) = "What is 1 + 1?"
questions(1) = "Who is the first man to walk on the Moon?"
questions(2) = "What is the name of the main character in the movie: Yes Man!(2007)"
questions(3) = "If I gave you three apples and you ate two, how many is left?"
questions(4) = "What do you want in your final grade?"
questions(5) = "What is the name of the thing(s) that you use whenever you eat?"
'Answers
answers(0) = "2"
answers(1) = "Neil Armstrong"
answers(2) = "Jim Carrey"
answers(3) = "1"
answers(4) = "A 4.0"
answers(5) = "A Spoon and Fork"
For i = 0 To questions.Count - 1
dtQAMain.Rows.Add(questions(i), answers(i)) 'assign QA in table for scoring purpose later
Next
End Sub
Private Sub loadQsAndAs()
Label1.Visible = False
For i = 0 To alAnsButton.Count - 1
alAnsButton(i).visible = True
Next
questionsCopy = New ArrayList
questionsCopy = questions.Clone 'close a copy so we dont effect the actual question copy when randomize and eliminate asked question from arraylist
TextBox1.Text = setTheQuestion()
setTheAnswer()
End Sub
Private Function setTheQuestion() As String
Dim randomValue As New Random
Dim randomQ As String = ""
Dim index As Integer
If questionsCopy.Count <> 0 Then
index = randomValue.Next(0, questionsCopy.Count - 1)
randomQ = questionsCopy(index)
questionsCopy.RemoveAt(index) 'asked question will be remove.
Else ' questions are finished, show the mark
ShowMark()
End If
Return randomQ
End Function
Private Sub setTheAnswer() 'randonmize the answer and assign to button
If TextBox1.Text = "" Then Exit Sub ' if question finish exit sub
Dim randomValue As New Random
Dim NewIndex As Integer
Dim temp As String
Dim answersCopy As ArrayList = answers.Clone
For n = answersCopy.Count - 1 To 0 Step -1
NewIndex = randomValue.Next(0, n + 1)
' Swap them.
temp = answersCopy(n)
answersCopy(n) = answersCopy(NewIndex)
answersCopy(NewIndex) = temp
Next
Dim AnswerRowCheck As Integer = questions.IndexOf(TextBox1.Text)
Dim ActualAnswer As String = dtQAMain.Rows(AnswerRowCheck).Item("A") 'check actual answer
Dim totalRemove As Integer = 0
For i = answersCopy.Count - 1 To 0 Step -1
If totalRemove = 2 Then Exit For
If answersCopy(i) <> dtQAMain.Rows(AnswerRowCheck).Item("A") Then
answersCopy.RemoveAt(i)
totalRemove += 1
End If
Next 'remove 2 of the selection,since only 4 button for answer selection and should not take out the actual answer
For i = 0 To alAnsButton.Count - 1
alAnsButton(i).text = answersCopy(i)
Next
End Sub
Private Sub ShowMark()
For i = 0 To alAnsButton.Count - 1
alAnsButton(i).text = "" 'clear the text, no more input receive from user.
Next
Label1.Visible = True
Label1.Text = totalScore & " out of 6 are correct."
End Sub
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
totalScore = 0
loadQsAndAs() 'refresh question
End Sub
Private Sub Button4_MouseClick(sender As Object, e As MouseEventArgs) Handles Button4.MouseClick, Button3.MouseClick, Button2.MouseClick, Button1.MouseClick
If sender.text = "" Then Exit Sub
Dim AnswerRowCheck As Integer = questions.IndexOf(TextBox1.Text) 'search question number
If dtQAMain.Rows(AnswerRowCheck).Item("A") = sender.text Then 'checking answer
totalScore += 1
End If
TextBox1.Text = setTheQuestion() 'next question
setTheAnswer()
End Sub
End Class
The code had cover most of the necessary comment which include the idea and how it work. Random() and arraylist are the key for this program to function, just pay more attention on it. Good luck.
How about trying this?
Public Class Form1
Dim questions(5) As String
Dim answers(5) As String
Private Sub loadQsAndAs()
'Questions
questions(0) = "What is 1 + 1?"
questions(1) = "Who is the first man to walk on the Moon?"
questions(2) = "What is the name of the main character in the movie: Yes Man! (2007)"
questions(3) = "If I gave you three apples and you ate two, how many is left?"
questions(4) = "What do you want in your final grade?"
questions(5) = "What is the name of the thing(s) that you use whenever you eat?"
'Answers
answers(0) = "2"
answers(1) = "Neil Armstrong"
answers(2) = "Jim Carrey"
answers(3) = "1"
answers(4) = "A 4.0"
answers(5) = "A Spoon and Fork"
Dim random As New Random
Dim indices = { 0, 1, 2, 3, 4, 5 }.OrderBy(Function (n) random.Next()).ToArray()
Dim question = random.Next(questions.Length - 1)
TextBox1.Text = questions(indices(question))
Button1.Text = answers(indices(0))
Button2.Text = answers(indices(1))
Button3.Text = answers(indices(2))
Button4.Text = answers(indices(3))
End Sub
End Class
That's it. Nice and simple. The key trick is creating a randomize indices array to do the lookups into the questions and answers arrays.
Private Dim rnd As Integer
Private Function setTheQuestion() As String
rnd = (CInt(Math.Ceiling(Rnd() * questions.Length)) + 1)
Return questions(rnd)
End Function
Private Function setTheAnswer1() As String
Return answers(rnd)
End Function

VB.NET Read .Txt File Into Multiple Text Boxes

I have a program that I can enter in names and integer values in the text boxes and then save those to a file. That works perfectly fine but the part I need help with is the reading of the file.
The data is saved into the file much like a csv file. example:
Test, 5, 5, 5
dadea, 5, 5, 5
das, 5, 5, 5
asd, 5, 5, 5
dsadasd, 5, 5, 5
My problem is, how do I read that into multiple text boxes on my form?
The names (first value of each row) should go into their corresponding Name textbox (i.e. txtName0, txtName1, txtName2, etc.) and the integer values should also go into their corresponding text boxes (txtCut1, txtColour1, etc.).
I have spent the past 2 hours trying to figure this out but I just cant.
The part I need help with is the last method.
Imports System.IO
Public Class Form1
Private aPricesGrid(,) As TextBox
Private aAverages() As TextBox
Private aNames() As TextBox
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
aPricesGrid = {{txtCut1, txtColour1, txtUpDo1, txtHighlight1, txtExtensions1},
{txtCut2, txtColour2, txtUpDo2, txtHighlight2, txtExtensions2},
{txtCut3, txtColour3, txtUpDo3, txtHighlight3, txtExtensions3},
{txtCut4, txtColour4, txtUpDo4, txtBHighlight4, txtExtensions4},
{txtCut5, txtColour5, txtUpDo5, txtHighlight5, txtExtensions5}}
aAverages = {txtAvg0, txtAvg1, txtAvg2, txtAvg3, txtAvg4}
aNames = {txtName0, txtName1, txtName2, txtName3, txtName4}
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
For nCol As Integer = 0 To 4
Dim nColTotal As Integer = 0
Dim nColItems As Integer = 0
For nRow As Integer = 0 To 2
Try
nColTotal += aPricesGrid(nRow, nCol).Text
nColItems += 1
Catch ex As Exception
End Try
Next
aAverages(nCol).Text = (nColTotal / nColItems).ToString("c")
Next
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
For Each txt As Control In Me.Controls
If TypeOf txt Is TextBox Then
txt.Text = String.Empty
End If
Next
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Dim oSaveFileDialog As New SaveFileDialog()
'Display the Common file Dialopg to user
oSaveFileDialog.Filter = "Text Files (*.txt)|*.txt"
If oSaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
' Retrieve Name and open it
Dim fileName As String = oSaveFileDialog.FileName
Dim outputFile As StreamWriter = File.CreateText(fileName)
For nRow As Integer = 0 To 4
outputFile.Write(aNames(nRow).Text)
For nCol As Integer = 0 To 2
outputFile.Write(", " & aPricesGrid(nRow, nCol).Text)
Next
outputFile.WriteLine()
Next
outputFile.Close()
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub ReadToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ReadToolStripMenuItem.Click
Dim oOpenFileDialog As New OpenFileDialog()
'Display the Common file Dialopg to user
oOpenFileDialog.Filter = "Text Files (*.txt)|*.txt"
If oOpenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim fileName As String = oOpenFileDialog.FileName
Dim OpenFile As StreamReader = File.OpenText(fileName)
End If
End Sub
End Class
Try this method.
Dim mindex as integer
Dim string1 as string()
Dim OpenFile As StreamReader = File.OpenText(fileName)
While OpenFile .Peek <> -1
string1= OpenFile .ReadLine.Split(",")
If mindex = 0 Then
txtname1.text=string1(0)
txtcut1.text=string1(1)
txtcolour1.text=string1(2)
'add other textboxes
ElseIf mindex = 1 Then
txtname2.text=string1(0)
txtcut2.text=string1(1)
txtcolour2.text=string1(2)
'add other textboxes
ElseIf mindex = 2 Then
txtname3.text=string1(0)
txtcut3.text=string1(1)
txtcolour3.text=string1(2)
'add other textboxes
ElseIf mindex = 3 Then
'your code
ElseIf mindex = 4 Then
'your code
End If
mindex += 1
End While
OpenFile .Close()
hope this helps.

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

Random Numbers to Text in Label

Public Class MainForm
Private Sub exitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles exitButton.Click
Me.Close()
End Sub
Private Sub guestsTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles guestsTextBox.KeyPress
' allows only numbers and the Backspace key
If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso
e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'fills the list box and selects the first item
typeListBox.Items.Add("Kid's Birthday")
typeListBox.Items.Add("21st Birthday")
typeListBox.Items.Add("40th Birthday")
typeListBox.Items.Add("Other Birthday")
typeListBox.SelectedIndex = 0
End Sub
Private Sub calcButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles calcButton.Click
'displays the total charge
Dim guests As Integer
Dim typeIndex As Integer
Dim guestPrice As Integer
Dim totalCharge As Integer
Integer.TryParse(guestsTextBox.Text, guests)
typeIndex = typeListBox.SelectedIndex
'determine the price per guest
Select Case typeIndex
Case 0 'Kid's Birthday
guestPrice = 11
Case 1 '21st Birthday
guestPrice = 20
Case 2 '40th Birthday
guestPrice = 25
Case Else 'other birthdays
guestPrice = 15
End Select
'calculate and display the total charge
totalCharge = guests * guestPrice
totalLabel.Text = totalCharge.ToString("C0")
End Sub
Private Sub testDataButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles testDataButton.Click
Dim guests As Integer
Dim typeIndex As Integer
Dim guestPrice As Integer
Dim totalCharge As Integer
Dim randomGen As New Random
Dim setCounter As Integer = 1
testDataLabel.Text = String.Empty
Do
guests = randomGen.Next(1, 51)
typeIndex = randomGen.Next(0, 4)
For Each I As Object In typeListBox.SelectedItems
testDataLabel.Text += I.ToString() & ControlChars.NewLine
Next
'determine the price per guest
Select Case typeListBox.SelectedIndex
Case 0
guestPrice = 11
Case 1
guestPrice = 20
Case 2
guestPrice = 25
Case Else
guestPrice = 15
End Select
'calculate and display the total charge
totalCharge = guests * guestPrice
testDataLabel.Text = testDataLabel.Text &
typeIndex.ToString & " " &
guests.ToString & " " &
totalCharge.ToString("C0") &
ControlChars.NewLine
setCounter += 1
Loop Until setCounter > 10
End Sub
Private Sub typeListBox_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles typeListBox.SelectedIndexChanged
End Sub
End Class
When I click on a button named "Generate Test Data" It generates a list of random numbers in a label. I want these numbers to say the type of birthday instead of the number.
0 being "Kid's Birthday"
1 being "21st Birthday"
2 being "40th Birthday"
and 3 being "Other Birthday"
How would I go about doing this?
Any help would be much appreciated!
If I understood your question correctly, you can declare an enum and have a dictionary of that enum to String.
The Enum takes care of dealing with numbers in code, and rather use human readable constructs. Dictionary will make sure your users will also see human readable constructs.
Please see below code (needs a brand new WinForms project and a ListBox called ListBox1 on the main form):
Option Strict On
Public Class Form1
'Declare this enum to avoid dealing with naked numbers in code
Enum BirthdayTypes
btKids = 0
bt21st = 1
bt40th = 2
btOther = 3
End Enum
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) _
Handles MyBase.Load
'Suppose your input value is a number,
'but you don't want to deal with numbers
Dim typeIndex As Integer = 2
'You can convert your number to BirthdayTypes,
'making your input "correct"
Dim typeIndexBt As BirthdayTypes = ConvertBirthdayIndexToType(typeIndex)
'Calculation of guest price is now "human readable"
Dim guestPrice As Integer = CalculateGuestPrice(typeIndexBt)
'You can create a dictionary for diplaying the values
Dim displayDictionary As New Dictionary(Of BirthdayTypes, String)
With displayDictionary
.Add(BirthdayTypes.btKids, "Kid's Birthday")
.Add(BirthdayTypes.bt21st, "21st Birthday")
.Add(BirthdayTypes.bt40th, "40th Birthday")
.Add(BirthdayTypes.btOther, "Other Birthday")
End With
'Here is how you would those values into a ListBox
With ListBox1
.DataSource = displayDictionary.ToList
.ValueMember = "Key"
.DisplayMember = "Value"
End With
'Now your ListBox displays strings,
'but SelectedValue would return an object of type BirthdayTypes
'You can extract random values from the above dictionary by index,
'and create a new list from it
Debug.WriteLine(ListBox1.SelectedValue) 'outputs btKids
End Sub
Private Function CalculateGuestPrice(bt As BirthdayTypes) As Integer
Select Case bt
Case BirthdayTypes.btKids : Return 11
Case BirthdayTypes.bt21st : Return 20
Case BirthdayTypes.bt40th : Return 25
Case BirthdayTypes.btOther : Return 15
End Select
'should never here
Throw New Exception("Unknown birthday type")
End Function
Private Function ConvertBirthdayIndexToType(index As Integer) As BirthdayTypes
If index < 3 Then Return CType(index, BirthdayTypes)
Return BirthdayTypes.btOther
End Function
End Class
Disclaimer: this code is just a demo of what can be done, not meant to be used a complete solution.
I would use a string.
Dim thestring() As String = {"Kid's Birthday", _
"21st Birthday", _
"40th Birthday", _
"Other Birthday"}
Now each of those numbers will represent the text in thestring.
thestring(0) = kids birthday
thestring(1) = 21 birthday
thestring(2) = 40th birthday
thestring(3) = other birthday
Make sense? I would help further, but i don't quite get what you are trying to do.