How to randomize a quiz on vbnet - vb.net

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

Related

need histogram from these results VB.net

I need some help with the histogram. My program counted the words with three, four, five and six letters. Now I need to make simple histogram from the received answers. This is my code:
Public Class Form1
Dim tekst As String
Dim rijec() As String
Dim trazena As String
Dim brojac1 As Integer = 1
Dim brojac2 As Integer = 0
Dim brojac3 As Integer = 0
Private Sub btnUcitaj_Click(sender As Object, e As EventArgs) Handles btnUcitaj.Click
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
RichTextBox1.Text = My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
End If
End Sub
Private Sub btnPrebroj1_Click(sender As Object, e As EventArgs) Handles btnPrebroj1.Click
tekst = RichTextBox1.Text
rijec = tekst.Split(CChar(" "))
Dim count = From x In rijec Where x.Length = 3
txtTri.Text = ("Number of words: " & count.Count.ToString())
End Sub
Private Sub btnPrebroj2_Click(sender As Object, e As EventArgs) Handles btnPrebroj2.Click
tekst = RichTextBox1.Text
rijec = tekst.Split(CChar(" "))
Dim count = From x In rijec Where x.Length = 4
txtCetiri.Text = ("Number of words: " & count.Count.ToString())
End Sub
Private Sub btnPrebroj3_Click(sender As Object, e As EventArgs) Handles btnPrebroj3.Click
tekst = RichTextBox1.Text
rijec = tekst.Split(CChar(" "))
Dim count = From x In rijec Where x.Length = 5
txtPet.Text = ("Number of words: " & count.Count.ToString())
End Sub
Private Sub btnPrebroj4_Click(sender As Object, e As EventArgs) Handles btnPrebroj4.Click
tekst = RichTextBox1.Text
rijec = tekst.Split(CChar(" "))
Dim count = From x In rijec Where x.Length = 6
txtSest.Text = ("Number of words: " & count.Count.ToString())
End Sub
i need histogram from these results from picture.
Visual Basic actually has a control called a chart which is nice for this kind of situation. I found a tutorial here if you would like to check it out.
I wrote up this function that should work with your code, all you need to do is add a data chart and call it Chart1 and call this function.
Private Sub ShowData()
Chart1.Series.Clear() ' Delete the default data series.
Dim tekst = RichTextBox1.Text
Dim rijec = tekst.Split(CChar(" "))
With Chart1.Series.Add("Word Lengths") ' Add a new series called Word Lengths
For wordLength As Integer = 3 To 6 ' Check every word length from 3 to 6
Dim count = From x In rijec Where x.Length = wordLength ' Count how many words there are
.Points.AddXY(wordLength, count.Count) ' Add a new data point
Next
End With
End Sub
Good luck, I hope this helped!
~Nic

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

Reading lines from a text file in VB

I'm creating a Quiz Application in VB and the quiz app reads the questions from a text file which is already created and it has got some questions in it.
1
Q.Who won the WorldCup last time?
I Don't know
May be he knows
Who knows
Who cares?
2
Question 2
Answer A
Answer B
Answer C
Answer D
3
Question 3
Ans 1
Ans 2
Ans 3
Ans 4
The first line is the question number,the second line is the question,lines 3 - 6 represents the answer choices.Now I have created a Form for quiz and when the next button is pressed it should display the next question i.e,After the first question it should go to Question 2 and print accordingly.But unfortunately i'm unable to calculate the logic to go to next question.
Public Class Quiz
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As Integer, ByVal lParam As Integer) As IntPtr
End Function
Dim SCORE As Integer = 0
Dim val As Integer = 30
Dim QUES As Integer = 0
Dim Line As Integer = 1
Dim allLines As List(Of String) = New List(Of String)
Dim TextFilePath As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Quiz.txt")
Private Sub Quiz_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 30
Timer1.Enabled = True
Next_Prev_Ques(Line + QUES)
End Sub
Public Function Next_Prev_Ques(quesno As Integer) As Integer
Line = quesno
Using file As New System.IO.StreamReader(TextFilePath)
Do While Not file.EndOfStream
allLines.Add(file.ReadLine())
Loop
End Using
QUES = ReadLine(Line, allLines)
Label1.Text = ReadLine(Line + 1, allLines)
RadioButton1.Text = ReadLine(Line + 2, allLines)
RadioButton2.Text = ReadLine(Line + 3, allLines)
RadioButton3.Text = ReadLine(Line + 4, allLines)
RadioButton4.Text = ReadLine(Line + 5, allLines)
Return Line
End Function
Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
Return lines(lineNumber - 1)
End Function
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
ProgressBar1.Value += 1
val -= 1
Label2.Text = val & " Sec"
If ProgressBar1.Value = ProgressBar1.Maximum Then
Timer1.Enabled = False
End If
If ProgressBar1.Value > 25 Then
SendMessage(ProgressBar1.Handle, 1040, 2, 0)
End If
End Sub
Private Sub Quiz_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Form1.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox(Line + QUES + 5)
Next_Prev_Ques(Line + QUES + 4)
Me.Refresh()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Next_Prev_Ques(Line + QUES + 5)
End Sub
The function Next_Prev_Ques Should run accordingly but its not.Can anyone post the correct code?
Below is some code that uses serialization to get the same results. You can create a class called Questions and properties on it like questionnumber, question and answer, store the data into a xml file and retrieve them with string methods. Check the code below:
The code for the class
Public Class clsQuestions
Private _Number As String
Private _Question As String
Private _Answer As String
Public Property Number() As String
Get
Number = _Number
End Get
Set(ByVal Value As String)
_Number = Value
End Set
End Property
Public Property Question() As String
Get
Question = _Question
End Get
Set(ByVal Value As String)
_Question = Value
End Set
End Property
Public Property Answer() As String
Get
Answer = _Answer
End Get
Set(ByVal Value As String)
_Answer = Value
End Set
End Property
End Class
The code for the form
Imports System.IO
Imports System.Xml.Serialization
Public Class Form1
Dim numQuestions() As String
Dim questions() As String
Dim answersGroup() As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Text = ""
Label2.Text = ""
Label3.Text = ""
Main()
End Sub
Private Sub Main()
Dim p As New clsQuestions
p.Number = "1,2,3,4,5,6,7,8,9,10"
p.Question = "Question 1,Question 2,Question 3," &
"Question 4,Question 5,Question 6,Question 7," &
"Question 8,Question 9,Question 10"
p.Answer = "Answer 1.1,Answer 1.2,Answer 1.3,Answer 1.4;" &
"Answer 2.1,Answer 2.2,Answer 2.3,Answer 2.4;" &
"Answer 3.1,Answer 3.2,Answer 3.3,Answer 3.4;" &
"Answer 4.1,Answer 4.2,Answer 4.3,Answer 4.4;" &
"Answer 5.1,Answer 5.2,Answer 5.3,Answer 5.4;" &
"Answer 6.1,Answer 6.2,Answer 6.3,Answer 6.4;" &
"Answer 7.1,Answer 7.2,Answer 7.3,Answer 7.4;" &
"Answer 8.1,Answer 8.2,Answer 8.3,Answer 8.4;" &
"Answer 9.1,Answer 9.2,Answer 9.3,Answer 9.4;" &
"Answer 10.1,Answer 10.2,Answer 10.3,Answer 10.4"
'Serialize object to a text file.
Dim objStreamWriter As New StreamWriter("C:\Users\Username\Documents\Questions.xml")
Dim x As New XmlSerializer(p.GetType)
x.Serialize(objStreamWriter, p)
objStreamWriter.Close()
'Deserialize text file to a new object.
Dim objStreamReader As New StreamReader("C:\Users\Username\Documents\Questions.xml")
Dim p2 As New clsQuestions
p2 = x.Deserialize(objStreamReader)
objStreamReader.Close()
numQuestions = p2.Number.Split(",")
questions = p2.Question.Split(",")
answersGroup = p2.Answer.Split(";")
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
Static x As Integer
If x <= questions.Length - 1 Then
Label1.Text = ""
Label2.Text = ""
Label3.Text = ""
arrayIndex(x)
x += 1
End If
End Sub
Private Sub arrayIndex(ByVal num As Integer)
Label1.Text = numQuestions(num)
Label2.Text = questions(num)
Dim answers() As String
answers = answersGroup(num).Split(",")
For Each item As String In answers
Label3.Text &= item & Environment.NewLine
Next
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

Error message whenever alphabet is entered rather than number

I m new to vb.net & I have a problem that whenever user enters an alphabet he/she will receive message that only numbers are allowed. For this code.... Please help me. I shall be very thankful to you.
Public Class Form1
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
If DataGridView1.CurrentCell.ColumnIndex = 0 Then
Dim combo As ComboBox = CType(e.Control, ComboBox)
If (combo IsNot Nothing) Then
RemoveHandler combo.SelectionChangeCommitted, New EventHandler(AddressOf ComboBox_SelectionChangeCommitted)
AddHandler combo.SelectionChangeCommitted, New EventHandler(AddressOf ComboBox_SelectionChangeCommitted)
End If
End If
End Sub
Private Sub ComboBox_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim combo As ComboBox = CType(sender, ComboBox)
If combo.SelectedItem = "Item1" Then
DataGridView1.CurrentRow.Cells(1).Value = "KG"
DataGridView1.CurrentRow.Cells(3).Value = "100"
DataGridView1.CurrentRow.Cells(2).Value = "Raw Material"
ElseIf combo.SelectedItem = "Item2" Then
DataGridView1.CurrentRow.Cells(1).Value = "Liter"
DataGridView1.CurrentRow.Cells(3).Value = "47"
DataGridView1.CurrentRow.Cells(2).Value = "Raw Material"
ElseIf combo.SelectedItem = "Item3" Then
DataGridView1.CurrentRow.Cells(1).Value = "Pound"
DataGridView1.CurrentRow.Cells(3).Value = "54"
DataGridView1.CurrentRow.Cells(2).Value = "Raw Material"
End If
End Sub
Private Sub Mul_Button_Click(sender As Object, e As EventArgs) Handles Mul_Button.Click
Dim s As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(3).Value)
Dim s1 As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(4).Value)
DataGridView1.CurrentRow.Cells(5).Value = s * s1
End Sub
Private Sub DataGridView1_CellValidated(sender As Object, e As EventArgs) Handles DataGridView1.CellValidated
Dim s As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(3).Value)
Dim s1 As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(4).Value)
DataGridView1.CurrentRow.Cells(5).Value = s * s1
If DataGridView1.RowCount > 0 Then
Dim sum As Integer
For index As Integer = 0 To DataGridView1.RowCount - 1
sum += Convert.ToInt32(DataGridView1.Rows(index).Cells(5).Value)
Next
TextBox1.Text = sum
End If
End Sub
Private Sub Add_Button_Click(sender As Object, e As EventArgs) Handles Add_Button.Click
If DataGridView1.RowCount > 0 Then
Dim sum As Integer
For index As Integer = 0 To DataGridView1.RowCount - 1
sum += Convert.ToInt32(DataGridView1.Rows(index).Cells(5).Value)
Next
TextBox1.Text = sum
End If
End Sub
End Class
Either wrap your code that has Convert.ToInt16() calls in them with Try/Catch blocks, or convert them to the Int16.TryParse() approach instead.
For example, this line:
Dim s As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(3).Value)
Could become:
Dim s As Int16
Dim strValue As String = DataGridView1.CurrentRow.Cells(3).Value
If Int16.TryParse(strValue, s) Then
' ... do something with "s" in here ...
' ... continue with code...
Else
MessageBox.Show(strValue, "Invalid Value")
End If