VB Import variable then use part 1 in dropdown and display part 2 to match selection in part 1 - vb.net

I'm using Visual studio to build a small utility.
I'm importing variables from a text file (this makes my program expandable in the future).
I'm running into a road block trying to split the variables into usable parts.
The text file is set up as such:
Game1:flshflhdlsfsdsfs
Game2:ugdjgndrgbdvdnjd
Game3:gnnereknengievke
And the code I've gathered from searching around trying to understand how I could do this is (It's gone through multiple rewrites but I feel this is probably the closest I've gotten):
Dim value As String = File.ReadAllText("Games.txt")
Dim cut_at As String = ":"
Dim x As Integer = InStr(value, cut_at)
Dim string_before As String = value.Substring(0, x - 2)
Dim string_after As String = value.Substring(x + cut_at.Length - 1)
Games_drp.Items.AddRange(string_before)
When I run a test like this, I get an error that String_before cannot be converted to an object. I tried switching "Dim string_before As String = value.Substring(0, x - 2)" to Dim string_before As Object = value.Substring(0, x - 2), but the dropdown that's supposed to be populated by at least one of the entries before the : has absolutely nothing in it.
Being pretty new at VB and feeling like I've exhausted pretty much every way I could think of searching in google and trying to piece together various bits of information, I figure I'd try asking my own direct question:
How would I go about reading all the lines from a text file, then splitting before the : to fill a combobox, and using a label to display the string after the : matching which ever entry is selected in the dropdown.
Thanks in advance for any help.
EDIT with full code:
Imports System.IO
Public Class Saves_frm
Private Sub Saves_frm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim value As String = File.ReadAllText("Games.txt")
Dim cut_at As String = ":"
Dim x As Integer = InStr(value, cut_at)
Dim string_before As String = value.Substring(0, x - 2)
Dim string_after As String = value.Substring(x + cut_at.Length - 1)
Games_drp.Items.AddRange(string_before)
End Sub
End Class
When run as is, I get an error that 'string_before' can't be converted from a string to an object, but when I make the following change from:
Dim string_before As String = value.Substring(0, x - 2)
to:
Dim string_before As Object = value.Substring(0, x - 2)
The error goes away, but the dropdown remains blank.

It's easier to use File.ReadAllLines, as it returns an array with all the file's lines. Then, you can loop through the lines, splitting each line and adding the result to the ListBox. This should be an example, but feel free to correct any mistakes I made, as I wrote it on my phone and it's been a long time since I used VB.
Dim lines() As String = File.ReadAllLines("file.txt")
For Each line As String In lines
Dim split() As String = line.Split(":"c)
gDic.Add(split(0), split(1))
Next
EDIT: Then, you most certainly want a dictionary that contains the name and the data, check the updated code.
Then, add the names by looping through gDic.Keys. When a name is selected, access its value with gDic("key").

Related

Saving contents of multiple text boxes and possibly combo boxes

I'm working on a basic application that lets you track experience earned across up to 3 skills. The names of the skills are in a combo box (not sure if the best) and the beginning and ending values are in text boxes.
I want to add a save button that saves the ending values and selected skills, when pressing the load button it would populate the combo boxes with saved skills and input the old ending values into the new beginning ones.
I've been working on this all day, searching for a long time I've come up with similar solutions but nothing seems to work right. I'm still a bit of a beginner so some of the solutions I don't understand. Also, this has to work for VBNet.
The closest solution I've come across is:
File.WriteAllText("C:\Data.txt", String.Join("|", new String({TextBox1.Text, TextBox2.Text, TextBox3.Text}))
I'd like the file to stay with the project in the main directory though. Would this work for combo boxes as well, and how to load the values back in?
I'm still a newbie to VB, hope this question makes sense.
If I get your idea right, please find some functions below if they can help:
One can read (or write) text:
This one can populate the needed string to 3 textboxes txtSkill1, txtSkill2, txtSkill3
Sub ReadTextFile()
Dim lineCount As Integer = 0
Dim rndInstance As New Random
Dim idx As Integer = 0
Dim selectedLine As String = ""
Dim txt As String = "Skills.txt"
If Not File.Exists(txt) Then
File.Create(txt).Dispose()
Dim objWriter As New System.IO.StreamWriter(txt, True)
' 2 sample text lines:
objWriter.WriteLine("Negotiating - Interpersonal - Working independently")
objWriter.WriteLine("Goal oriented - Leadership - Teamwork")
objWriter.Close()
End If
lineCount = File.ReadAllLines(txt).Length
idx = rndInstance.Next(1, lineCount + 1) ' the index can be random if you want, or run from (1 to lineCount)
selectedLine = ReadLineWithNumberFrom(txt, idx)
Dim pattern As String = "-" ' split on hyphens
Dim subStrings() As String = Regex.Split(selectedLine, pattern)
txtSkill1.Text = subStrings(0)
txtSkill2.Text = subStrings(1)
txtSkill3.Text = subStrings(2)
End Sub
One can read a string from a specific line number:
Function ReadLineWithNumberFrom(filePath As String, ByVal lineNumber As Integer) As String
Using file As New StreamReader(filePath)
' Skip all preceding lines:
For i As Integer = 1 To lineNumber - 1
If file.ReadLine() Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
Next
' Attempt to read the line you're interested in:
Dim line As String = file.ReadLine()
If line Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
' Succeeded!
Return line
End Using
End Function
Now with the functions allow you to write to any text file, to read from any text file, from any line number, with specific separator (here is the hyphen -- char), you can Save and Load any string you need.

VB Loading a list of variables from a text document

I'm currently trying to load a list of variables that are formatted like this:
5,
6,
3,
3,
etc, and I'm trying to output them to variables like this:
Strength = variablesList(1)
Agility = variablesList(2)
But so far, I've not been able to find a solution that seems to work for what I'm trying to do.
I'm currently working with:
Dim destination As String = Environment.GetFolderPath("C:\Roll20Output\Class" + outputClass + "2.txt")
Dim FileReader1 As New StreamReader(destination)
Dim Contents1 As String
Dim index As Integer = 0
While FileReader1.Peek <> -1
Contents1 = FileReader1.ReadLine
Dim array As New ArrayList
array.AddRange(Contents1.Split(","))
variablesList.Add(array)
End While
Strength = variablesList(1)
Agility = variablesList(2)
But so far I can't seem to get anything to output.
Would anyone be able to help?
Thanks
You are using a lot of outdated stuff in your code (reading a file with StreamReader, ArrayList instead of List<T>, etc.). I would suggest the following (untested):
' Returns an array with one string per line
Dim lines = File.ReadAllLines("C:\...\SomeFile.txt")
' Remove trailing `,` - LINQ magic
lines = (From s In lines Select s.TrimEnd(","c)).ToArray()
Dim strength = CInt(lines(0))
Dim agility = CInt(lines(1))
...
If you get rid of the useless trailing commas, you can skip the second step. If you use only commas instead of new lines, the first step becomes:
Dim lines = File.ReadAllText("C:\...\SomeFile.txt").Split(","c)

How to convert a string expression to vb code?

I have a string output from user interface as below,
strFormula ="gridControlName.Rows(i).cells("C1").value *
gridControlName.Rows(i).cells("C2").value"
if i write code like
dblRes=gridControlName.Rows(i).cells("C1").value *
gridControlName.Rows(i).cells("C2").value
it will give result.. but since its a string i could not get result
How can I remove the double quotes from the above string and get the values entered in the grid cells to be multiplied?
I don't think there's an 'easy' way to do this, since VB.Net doesn't have an "eval()" like some other languages. However, it does support run-time compilation. Here are a couple articles which may help you:
Using .NET Languages to make your Application Scriptable (VB.Net example)
Runtime Compilation (A .NET eval statement) (C# example)
Both are intended to be a bit more robust than just executing single lines of code, allowing users to input entire textboxes of their own code for example, but should give you some direction. Both include sample projects.
Hi guys thanks for your updates.. I wrote my own function by using your concepts and some other code snippets .I am posting the result
Function generate(ByVal alg As String, ByVal intRow As Integer) As String Dim algSplit As String() = alg.Split(" "c)
For index As Int32 = 0 To algSplit.Length - 1
'algSplit(index) = algSplit(index).Replace("#"c, "Number")
If algSplit(index).Contains("[") Then
Dim i As Integer = algSplit(index).IndexOf("[")
Dim f As String = algSplit(index).Substring(i + 1, algSplit(index).IndexOf("]", i + 1) - i - 1)
Dim grdCell As Infragistics.Win.UltraWinGrid.UltraGridCell = dgExcelEstimate.Rows(intRow).Cells(f)
Dim dblVal As Double = grdCell.Value
algSplit(index) = dblVal
End If
Next
Dim result As String = String.Join("", algSplit)
'Dim dblRes As Double = Convert.ToDouble(result)
Return result
End Function
Thanks again every one.. expecting same in future

loop - reading text after a certain string up until a certain string

start=AKS-RHzlSXSftLGYdBNk.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1&
For every instance of the word 'start' I need to be able to get the text after the first full stop, right up until the & symbol. E.g. 'eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1'.
There will be more than one instance of this. They will need to be appended to a listbox.
What is the simplest/quickest way to do this? (Using possibly streamreader - text file)
The simplest and quickest way will be to read each line, and check if it .StartsWith("start="). If so, then get the .IndexOf(".") and the .IndexOf("&", <whereever the first indexOf was>). Get the .SubString which encompasses those two values. I'm sure you can write the code yourself from that ;)
I tested this function with a button click, output text each line on a textbox. I am sure you can adapt this to your code.
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
txtResults.Text = ""
Dim ParseString As String
ParseString = "start=123341.23124&kjdshfkjsdaksdstart=1231.2321312&kadhskjashdkjastart=1231.23126789898&skjdfhkjsd"
Dim Delimiters() As String = New String() {"start="}
Dim Words() As String
Words = ParseString.Split(Delimiters, CompareMethod.Text)
For Each Part In Words
Dim Middle As String
Middle = Part.Split(".").Skip(1).Take(1).FirstOrDefault()
Dim Good As String
Good = Middle.Split("&").FirstOrDefault()
txtResults.Text += Good + vbNewLine
Next
End Sub
Output was
23124
2321312
23126789898
Added 31104 lines to a string and ran, took about 11 seconds to run on my laptop. Might be too slow for your app?

Adding values to array

I am trying to run an event which will search through the different files in a given directory. The goal is to have it search for all files that begin with 'SP_', which are .sql files containing Stored Procedures. I would then like to add the full text of these Procedures to an array to be used later. This is causing an error when run, which I believe is because 'FullProcedureArray()', the string array I am trying to load does not have defined boundaries. When I declare it as 'FullProcedureArray(7)', or with some other value, it appears to run fine. But I don't want to have to hard-code a boundary for 'FullProcedureArray'; I would rather let it be defined by whatever the number of files in the folder is.
My question: Is there a way to declare 'FullProcedureArray' without having to give it an absolute value? I may just be missing something painfully obvious, but I haven't worked with this type of array much in the past. Thanks in advance for your help.
Dim AppDataLocation As String = "C:\Files\TestFiles\"
Dim ProcedureArray As String()
Dim ProcedureText As String
Dim FullProcedureArray() As String
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(AppDataLocation)
Dim fileSystemInfo As System.IO.FileSystemInfo
Dim i As Integer = 0
For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
If (fileSystemInfo.Name.Contains("SP_")) Then
ProcedureArray = System.IO.File.ReadAllLines(AppDataLocation & fileSystemInfo.Name)
ProcedureText = Join(ProcedureArray, "")
FullProcedureArray.SetValue(ProcedureText, i)
i = (i + 1)
End If
Next
An array by definition has a fixed upper bound. If you don't want a fixed upper bound, don't use an array. Use, for example, a List(Of String) instead:
Dim AppDataLocation As String = "C:\Files\TestFiles\"
Dim ProcedureList As New List(Of String)
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(AppDataLocation)
For Each fileSystemInfo As System.IO.FileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
If (fileSystemInfo.Name.Contains("SP_")) Then
Dim ProcedureText As String = _
System.IO.File.ReadAllText(AppDataLocation & fileSystemInfo.Name)
ProcedureList.Add(ProcedureText)
End If
Next
If, for some reason, you still need the result as an array afterwards, simply convert the list to an array:
Dim myArray() As String = ProcedureList.ToArray()
If you don't want to give a size to your array or want to change at runtime, you can use "Redim Preserve"
http://msdn.microsoft.com/en-us/library/w8k3cys2%28v=vs.71%29.aspx