literate for each loop my string in VB.Net - 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.

Related

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

Set string values inside for without knowing names

I am trying to find the correct way to set the string values inside the For without knowing the actual numbers. here's what i am trying to do as it was possible in vb6 but not sure using vb.net
Public Class Form1
Dim iTest1 As String
Dim iTest2 As String
Dim iTest3 As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i = 1 To 3
"iTest" & i = "aaa" & i
Next
Debug.Print("iTest1:" & iTest1)
Debug.Print("iTest2:" & iTest2)
Debug.Print("iTest3:" & iTest3)
End Sub
End Class
Try using Arrays instead.
Dim iTest(3) As String
For i = 1 To 3
iTest(i) = "aaa" & i
Next
Or this
Dim variables As New Dictionary(Of String, String)()
For i = 1 To 3
variables("iTest" + i.ToString) = "aaa" & i
Next
Console.WriteLine("iTest1:" + variables("iTest1"))
Console.WriteLine("iTest2:" + variables("iTest2"))
Console.WriteLine("iTest3:" + variables("iTest3"))
It's technically possible, but not really a recommended approach...
If you make the variables Public, then you can use the legacy CallByName() function brought over from VB6:
Public Class Form1
Public iTest1 As String
Public iTest2 As String
Public iTest3 As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 1 To 3
CallByName(Me, "iTest" & i, CallType.Let, "aaa" & i)
Next
Debug.Print("iTest1:" & iTest1)
Debug.Print("iTest2:" & iTest2)
Debug.Print("iTest3:" & iTest3)
End Sub
End Class
Without CallByName(), this can be accomplished via Reflection. Note that this works with Private or Public variables:
Public Class Form1
Private iTest1 As String
Private iTest2 As String
Private iTest3 As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim T As Type = Me.GetType
For i As Integer = 1 To 3
Dim F As Reflection.FieldInfo = T.GetField("iTest" & i, Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
If Not IsNothing(F) Then
F.SetValue(Me, "aaa" & i)
End If
Next
Debug.Print("iTest1:" & iTest1)
Debug.Print("iTest2:" & iTest2)
Debug.Print("iTest3:" & iTest3)
End Sub
End Class

Formatting a drive in Visual Basic?

I have a ListBox that is being populated only with removable drives. The user selects the drives to be formatted and then the program should format those drives. However, I get the message that the specified file cannot be found. Here is my code.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each Drive In My.Computer.FileSystem.Drives
'Gets drive letter and type
Dim DriveInfo As String = Drive.Name & " (" & Drive.DriveType.ToString & ")"
'Checks to see if drive is a removable drive
Dim removable = "Removable"
Dim isFlashDrive As Boolean = DriveInfo.Contains(removable)
'Adds only removable drives to the list
If isFlashDrive Then
ListBox1.Items.Add(DriveInfo)
End If
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs)
'Variables initialized
Dim i, j As Integer
Dim s, DrvsToFormat As String
'Stores all selected drives in an array named "drives" and creates string with drive letter
Dim drives(ListBox1.SelectedItems.Count) As String
For i = 0 To ListBox1.SelectedItems.Count - 1
s = ListBox1.SelectedItems(i).ToString.Substring(0, 2)
drives(i) = s
DrvsToFormat = DrvsToFormat & " " & ListBox1.SelectedItems(i).ToString.First()
Next
Dim response = MessageBox.Show("Are you sure you want to format drive(s) " & DrvsToFormat & "? All data will be lost.", "WARNING!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
If response = MsgBoxResult.Yes Then
For j = 0 To drives.Length() - 1
Console.WriteLine(drives(j))
Process.Start("format " & drives(j))
Next
MessageBox.Show("Format Complete!")
End If
End Sub
End Class
The problem is that Process.Start does not take command line arguments in the first parameter. Use the overload that allows command line arguments.
For example:
Process.Start("format.com", "H:");

Recognize Variable Globally in VB.NET

How to Recognize Variable Globally in VB.NET? I have the code below, my problem is that VB.NET does not recognize the variables "Z_lenght" and "Z_width" outside the IF Statement (i.e. after ENDIF).
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text > TextBox2.Text Then
Dim Z_lenght = TextBox1.Text
Dim Z_width = TextBox2.Text
Else
Dim Z_lenght = TextBox2.Text
Dim Z_width = TextBox1.Text
End If
Dim Z_area = Z_lenght * Z_width
RichTextBox1.AppendText("Length = " & Z_lenght)
RichTextBox1.AppendText("Width = " & Z_width)
RichTextBox1.AppendText("Area = " & Z_area)
End Sub
End Class
I appreciate any help/comment.
Public Class Form1
Dim Z_length As Double = 0
Dim Z_width As Double = 0
Dim Z_area As Double = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text > TextBox2.Text Then
' I don't know what you're trying to achieve here,
' but I recommend try using Double.TryParse()
Double.TryParse(TextBox1.Text, Z_length)
Double.TryParse(TextBox2.Text, Z_width)
Else
Double.TryParse(TextBox2.Text, Z_length)
Double.TryParse(TextBox1.Text, Z_width)
End If
Z_area = Z_length * Z_width
RichTextBox1.AppendText("Length = " & Z_length)
RichTextBox1.AppendText("Width = " & Z_width)
RichTextBox1.AppendText("Area = " & Z_area)
End Sub
End Class
This will make Z_Length, Z_width and Z_area usable in class Form1
declare your variables outside of the if else scope.
http://msdn.microsoft.com/en-us/library/1t0wsc67.aspx
If you declare a variable within a block, you can use it only within
that block. In the following example, the scope of the integer
variable cube is the block between If and End If, and you can no
longer refer to cube when execution passes out of the block.
Given your comments, it seems you should review variable scopes. You can use your variables outside your if-else inside your if-else.

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))