Index Val List VB.Net - vb.net

I have a Listbox called ListTxtDrawR4. Every time I select an item, I want to display the value corresponding to the index in a textbox with name TxtNumberListScan.Lines(i). for example, if I select the 5th line in ListTxtDrawR4, I want to display the value of line 5 from TxtNumberListScan in another Textbox. how do I do that?
TxtTop10HighestResult.Text &= Environment.NewLine & TxtNumberListScan.Lines(TxtTop10HighestCount.Lines(0))
TxtTop10HighestResult.Text &= Environment.NewLine & TxtNumberListScan.Lines(TxtTop10HighestCount.Lines(1))
TxtTop10HighestResult.Text &= Environment.NewLine & TxtNumberListScan.Lines(TxtTop10HighestCount.Lines(2))
TxtTop10HighestResult.Text &= Environment.NewLine & TxtNumberListScan.Lines(TxtTop10HighestCount.Lines(3))
TxtTop10HighestResult.Text &= Environment.NewLine & TxtNumberListScan.Lines(TxtTop10HighestCount.Lines(4))
TxtTop10HighestResult.Text &= Environment.NewLine & TxtNumberListScan.Lines(TxtTop10HighestCount.Lines(5))

Names of controls have been changed to protect the innocent. (I watch Dragnet :-)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'This is just some data to test with
Dim A() As String = {"Mathew", "Mark", "Luke", "John"}
Dim B() As String = {"Peter", "Paul", "James", "Judas"}
ListBox1.Items.AddRange(A)
For Each s In B
TextBox1.Text &= s & Environment.NewLine
Next
TextBox1.Text.TrimEnd() 'Remove final new line
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim index As Integer = ListBox1.SelectedIndex
'Check that the index does not exceed the number of lines.
If index < TextBox1.Lines.Count Then
Dim StringToCopy = TextBox1.Lines(index)
TextBox2.Text &= StringToCopy & Environment.NewLine
End If
End Sub

Related

literate for each loop my string in VB.Net

Dim txtLinqSum1Ad, txtLinqSum2Ad, txtLinqSum3Ad, txtLinqSum4Ad as String
instead of writing this thing
TextBox1.AppendText(txtLinqSum1Ad & vbNewLine)
TextBox1.AppendText(txtLinqSum2Ad & vbNewLine)
TextBox1.AppendText(txtLinqSum3Ad & vbNewLine)
TextBox1.AppendText(txtLinqSum4Ad & vbNewLine)
I would like to do something like that
For i as integer = 0 to 3
TextBox1.AppendText(txtLinqSum & i & Ad & vbNewLine)
Next
Do you think that could be possible? it would be useful when I have a lot of strings?
Yes, it's possible with CallByName(), or via Reflection (much longer syntax).
For CallByName() to work, though, your variables have to be PUBLIC at Form/Class level:
Public Class Form1
Public txtLinqSum1Ad, txtLinqSum2Ad, txtLinqSum3Ad, txtLinqSum4Ad As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txtLinqSum1Ad = "A"
txtLinqSum2Ad = "B"
txtLinqSum3Ad = "C"
txtLinqSum4Ad = "D"
End Sub
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click
For i As Integer = 1 To 4
Dim s As String = CallByName(Me, "txtLinqSum" & i & "Ad", CallType.Get)
TextBox1.AppendText(s & vbNewLine)
Next
End Sub
End Class
But just because you can, doesn't mean you should. An array or other type of collection (List/Dictionary) would probably be a better choice.

Saving multiple items in a ComboBox control in VB.NET

I'm working on a student grading system and I want a suggestion to save all the data that were entered in the TextBox Controls into a text file, but I'm facing a problem. In my program the student can select multiple courses from the ComboBox Control and enter a grade for each one of them.
How can I save all the selected items from the ComboBox control with the grades entered for the same student?
For example: A student enters his name Adam K., and Adam K. selected six courses and put grades for each one of them.
How can I save all these pieces of information in order to be displayed like the following?
Adam K. , history 98/100, math 56/100, geography 78/100 and so on.
Since the information you describe is not very clear, I can only try to provide you with a solution based on the information you provide.
The effect is as follows:
In test.txt file:
You can try my method if you want this effect.
Public Class Form1
Dim name As String
Dim info As New Dictionary(Of String, String)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim course As String() = {"History", "Math", "English", "Chinese", "Science", "Biology"}
For Each item As String In course
ComboBox1.Items.Add(item)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ComboBox1.Text IsNot "" Then
If TextBox2.Text Is "" Then
Try
info.Add(ComboBox1.Text, "0 / 100") 'score default
Catch
MsgBox("The course " & ComboBox1.Text & " already exists.")
End Try
Else
Try
info.Add(ComboBox1.Text, TextBox2.Text & "/100")
Catch
MsgBox("The course " & ComboBox1.Text & " already exists.")
End Try
End If
Else
MsgBox("Please enter course info")
End If
ComboBox1.Text = "" 'clear course info
TextBox2.Text = ""
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
name = TextBox1.Text
TextBox3.Text &= name & " "
For Each kvp As KeyValuePair(Of String, String) In info
TextBox3.Text &= kvp.Key.ToString & ":" & kvp.Value.ToString & " "
Next kvp
TextBox3.Text &= vbCrLf
TextBox1.Text = ""
info.Clear() 'clear all info
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim file As System.IO.StreamWriter 'Write Text to Files with a StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("D:\test.txt", True)
file.WriteLine(TextBox3.Text)
file.Close()
TextBox3.Text = "" 'Append to Text Files in Visual Basic
'Dim inputString As String = "This is a test string."
'My.Computer.FileSystem.WriteAllText("D:\test.txt", inputString, True)
End Sub
End Class

Sync Two Textbox Lines VB.Net

How do I sync 2 Textboxes? I mean, if I randomize the first Textbox (Randomize Text Lines) how do the 2nd Textbox be synchronized after the first Textbox?
I also want the 4 Textboxes containing the items to be saved in (Answer.dat) for example if in the first Textbox I have the element (BlackJack) in the 2nd Textbox element (21) in the 3rd Textbox the Poker element and the fourth Textbox element Bingo.
I want to save this in the new line (in my text file) to be something like the model (Blank Empty + Word(Textbox3) + Space + Word(Textbox4) + Space + Word(Textbox5) + Space + Word(Textbox6) this is the Screenshot how the items want to be saved. Unfortunately, I'm not doing too well with the blank at first.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.Text = System.IO.File.ReadAllText(My.Application.Info.DirectoryPath + ("\Data\Question.dat"))
TextBox2.Text = System.IO.File.ReadAllText(My.Application.Info.DirectoryPath + ("\Data\Answer.dat"))
End Sub
End Class
So how can I do to save in a new line of Textbox (Save to my text file) the question and the answers in the textbox? following the example given?
The code below will keep the rows synchronized on a random shuffle. If you don't want repeated rows, you will have to code validation to throw-out draws that have already occurred.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim text1 As String
Dim text2 As String
Dim textarray1 As New ArrayList
Dim textarray2 As New ArrayList
Dim NextMember As String = ""
Dim Rand As New Random
Dim RandNum As Integer = 0
TextBox1.Clear()
TextBox2.Clear()
text1 = "one" & vbCrLf & "two" & vbCrLf & "three" & vbCrLf
text2 = "A" & vbCrLf & "B" & vbCrLf & "C" & vbCrLf
For i = 1 To Len(text1)
Do Until Mid(text1, i, 1) = vbCr
NextMember = NextMember & Mid(text1, i, 1)
i = i + 1
Loop
textarray1.Add(NextMember)
i = i + 1
NextMember = ""
Next
For i = 1 To Len(text2)
Do Until Mid(text2, i, 1) = vbCr
NextMember = NextMember & Mid(text2, i, 1)
i = i + 1
Loop
textarray2.Add(NextMember)
i = i + 1
NextMember = ""
Next
For i = 0 To textarray1.Count - 1
RandNum = Rand.Next(textarray1.Count)
TextBox1.Text = TextBox1.Text & textarray1(RandNum) & vbCrLf
TextBox2.Text = TextBox2.Text & textarray2(RandNum) & vbCrLf
Next
End Sub

search and count occurances of a word in a textbox string

Right now I have two textboxes. One is the input and the other the text string. It functions perfectly. Is there a way to get rid of the input box and have the "searched" word in the code so when I hit a button it gives the result.
Private Function FindWords(ByVal TextSearched As String, ByVal Paragraph As String) As Integer
Dim location As Integer = 0
Dim occurances As Integer = 0
Do
location = TextSearched.IndexOf(Paragraph, location)
If location <> -1 Then
occurances += 1
location += Paragraph.Length
End If
Loop Until location = -1
Return occurances
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Label1.Text = TextBox2.Text ' display result
Label2.Text = FindWords(TextBox1.Text, TextBox2.Text)
' MsgBox("The word " & TextBox2.Text & " has occured " & FindWords(TextBox1.Text, TextBox2.Text) & " times!!")
End Sub
There are a couple of small problems that you'll might see of you turn on option strict in your project's compile settings. Your function returns an integer. To properly assign it to a textbox label, you should really add .ToString to the end of the assignment like this
Label2.Text = FindWords(TextBox1.Text, TextBox2.Text).ToString
So leaving you code as you wrote it, in this sub, you just want to pass a string as the parameter for the text to find?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Label1.Text = TextBox2.Text ' display result
Label2.Text = FindWords(TextBox1.Text, TextBox2.Text)
' MsgBox("The word " & TextBox2.Text & " has occured " & FindWords(TextBox1.Text, TextBox2.Text) & " times!!")
End Sub
Just change it to this
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
dim searchString as string="Hello" 'or whatever string you want to use
Label1.Text = TextBox2.Text ' display result
Label2.Text = FindWords(searchString, TextBox2.Text)
' MsgBox("The word " & TextBox2.Text & " has occured " & FindWords(TextBox1.Text, TextBox2.Text) & " times!!")
End Sub
but it might be better to change it a bit more so that your function only gets executed once if you want to display a messagebox with the number of occurences - like this
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
dim searchCount as Integer
dim searchString as string="Hello" 'or whatever string you want to use
Label1.Text = TextBox2.Text ' display result
searchCount = FindWords(searchString, TextBox2.Text)
Label2.Text = searchcount.ToString
' MsgBox("The word " & TextBox2.Text & " has occured " & searchcount.Tostring & " times!!")
End Sub

vb.net Searching for specific lines within large .log files

I'm reading from 1-5mb log files outputting to a textview and also searching for specific lines outputting to another textview. Currently it takes about a minute for just a 1mb file. Does anyone know any faster methods of searching through lines or strings other than the method I'm using?
Imports EnterpriseDT.Net.Ftp
Public Class Form1
Private Sub SettingsToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles SettingsToolStripMenuItem.Click
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim sw As New Stopwatch
Dim FullLine As String = ""
Dim ScriptLine As String = ""
sw.Start()
Dim ll As New Queue(Of String)
Dim i As String = ""
Using TestFile As New IO.StreamReader("c:\test.txt", System.Text.Encoding.Default, False, 4096)
Using OutFile As New IO.StreamWriter("c:\SBOutFile.txt", False, System.Text.Encoding.Default, 4096)
While TestFile.EndOfStream = False
i = TestFile.ReadLine
If i.Contains(".sqf") And i.Contains("handleGear.sqf") = False Then
ScriptLine = ScriptLine & i & vbNewLine & vbNewLine
FullLine = FullLine & i & vbNewLine & vbNewLine
Else
FullLine = FullLine & i & vbNewLine & vbNewLine
End If
End While
End Using
End Using
sw.Stop()
TextBox1.Text = FullLine
TextBox2.Text = ScriptLine
RichTextBox1.AppendText(String.Format("Run_Queue took {0} Milliseconds." & Environment.NewLine, sw.ElapsedMilliseconds))
End Sub
Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Try
'connect to ftp server
Dim ftp As New FTPConnection
ftp.ServerAddress = "-"
ftp.ServerPort = "-"
ftp.UserName = "-"
ftp.Password = "-"
ftp.Connect()
ftp.ChangeWorkingDirectory("-")
ftp.TransferType = FTPTransferType.BINARY
'download a file
ftp.DownloadFile("c:\test.txt", "scripts.log")
'ftp.RenameFile("scripts.log", "scripts_test.log")
'close the connection
ftp.Close()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
End Sub
End Class
Given the heavy reading and concatenating you are doing as you're reading, I suspect its part of your time/performance issue. I would probably consider changing the declarations for ScriptLine and FullLine from String type to a StringBuilder, because Strings are technically immutable. That means each concatenation really turns out to be teardown of the previous object, and the creation of a new one in its place. StringBuilders are designed specifically for heavy concatenation scenarios. When the looping is finished, you can convert it back to a String.
Also, a compiled Regular Expression might search faster than String.Contains. Your regular expression string would be something like "(?!handleGear).sqf", meaning "find any sequence of zero or more characters other than "handleGear" in front of the string ".sqf".
I haven't had a chance to test that expression, so it is offered with that caveat. If I get a chance to throw together a test, I'll be glad to amend and let you know.
Good luck!
I just wanted to post what I came up with in the end. It was a very large improvement to what I had.
'Read file
Dim sw As New Stopwatch
Dim FullLine As String = ""
Dim ScriptLine As String = ""
sw.Start()
Dim ll As New Queue(Of String)
Dim i As String = ""
Dim builder As New StringBuilder
Using TestFile As New IO.StreamReader("c:\test.txt", System.Text.Encoding.Default, False, 4096)
builder.AppendLine("Started at: " & DateTime.Now.ToLongTimeString().ToString)
RichTextBox1.AppendText(Now.ToShortTimeString & " Reading Log File Started" & vbNewLine)
RichTextBox1.SelectionStart = RichTextBox1.TextLength
Dim rowCount As Integer = 0
Do Until TestFile.EndOfStream
ScriptLine = TestFile.ReadLine
ScriptLine = LCase(ScriptLine)
If InStr(ScriptLine, ".sqf") > 0 And InStr(ScriptLine, "handlegear.sqf") < 1 Then 'And InStr(ScriptLine, "createmarkerlocal.sqf") < 1 And InStr(ScriptLine, "setmarkerposlocal.sqf") < 1
builder.AppendLine(ScriptLine)
builder.AppendLine()
End If
rowCount = rowCount + 1
Loop
builder.AppendLine(Now.ToShortTimeString & "==== Searched " & rowCount & " rows" & vbNewLine)
builder.AppendLine(Now.ToShortTimeString & " Finished" & vbNewLine)
End Using
sw.Stop()
RichTextBox2.AppendText(builder.ToString & vbNewLine)
RichTextBox1.AppendText(Now.ToShortTimeString & String.Format(" Run_Queue took {0} Milliseconds." & Environment.NewLine, sw.ElapsedMilliseconds))