extract parts of a text line into multiple variables in vb.net - vb.net

I have created a program that uses the dictionary object to read a line for a TXT file and populate 2 listboxes. It is a bilingual dictionary.
In the file the lines have the structure:
key^value (word in 1st language and word in 2nd language divided by the ^ separator)
e.g.
before^prima
later^dopo
hello^ciao
and the code works just fine...
the problem is that i now need to transform it in a multilingual dictionary so the structure would be
key^value1^value2^value3 (words in 4 languages all divided by the separator)
but i am not able to adapt the dictionary object to it.
How would you solve this?
Basically i have a bunch of lines that are formed by 4 parts with separator and i want to store all the 4 parts in 4 variables:
- definition
- 1stlang
- 2ndlang
- 3rdlang
The code i am using so far for the bilingual is this:
Public Class aero_dictionary
Dim dict As New Dictionary(Of String, String)
Private Sub Form1_Deactivate(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Deactivate
Me.Opacity = 0.6
End Sub
Private Sub Form1_Activated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Activated
Me.Opacity = 1
End Sub
Private Sub button1_Click(sender As System.Object, _
e As System.EventArgs) _
Handles Button1.Click
Using OFD As New OpenFileDialog
With OFD
.Filter = "Dict files (*.dict)|*.dict"
If .ShowDialog = Windows.Forms.DialogResult.OK Then
LeggiDizionario(.FileName)
End If
End With
End Using
End Sub
Private Sub LeggiDizionario(FullPathFileName As String)
Dim lines As String() = IO.File.ReadAllLines(FullPathFileName)
For Each line As String In lines
Dim kv As KeyValuePair(Of String, String) = ToKeyValuePair(line)
dict.Add(kv.Key, kv.Value)
ListBox1.Items.Add(kv.Key)
Next
End Sub
Public Function ToKeyValuePair(pair As String) _
As KeyValuePair(Of String, String)
Dim two As String() = pair.Split("^")
Return New KeyValuePair(Of String, String)(two(0), two(1))
End Function
Private Sub listbox1_Click(sender As Object, _
e As System.EventArgs) _
Handles ListBox1.Click
Dim lst As ListBox = DirectCast(ListBox1, ListBox)
TextBox2.Clear()
TextBox2.SelectedText = dict(lst.SelectedItem)
End Sub
End Class

You can define the dictionary to use an array of strings, then add the array of 3 elements (less the key) when you the dict.Add.
Dim dict As New Dictionary(Of String, String())

Related

How to declare a dictionary using a name the user specifies?

Obviously I cannot use strName in the Dictionary declaration line, but I'm just placing it there to represent what I'm trying to do. For example, if the User enters "carrot", I want the dictionary created to be named carrot. Is there a way to do this?
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strName As String
strName = TextBox1.Text
Dim strName As New Dictionary(Of String, String)
End Sub
End Class
You can't. The name is useful for debugging and in reality the compiler will not use the name anyway - the name will be kept in the pdb file, nowhere else.
If you need to keep track of some dictionary by name, you could use another dictionary such as:
Private dictionaries As New Dictionary(Of String, Dictionary(Of String, String))()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strName = TextBox1.Text
Dim myNamedDictionary As Dictionary(Of String, String)
If dictionaries.ContainsKey(strName) Then
myNamedDictionary = dictionaries(strName)
Else
myNamedDictionary = New Dictionary(Of String, String)()
dictionaries.Add(strName, myNamedDictionary)
End If
' now you have a dictionary for the name you entered (carrot)
End Sub
To retrieve
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim carrotDictionary = dictionaries("carrot")
End Sub
I think this is as close as you will get.
You can, kind of. Using a compiler you can compile your own code, but the end result seems so unusable, I doubt this is what you want to do
Option Strict Off
Imports System.Reflection
Imports System.CodeDom.Compiler
Public Class Form1
Private dictionaryInstance As Object
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strName = TextBox1.Text
Dim t = GetType(Form1)
Dim ns = t.Namespace
Dim provider = New VBCodeProvider()
Dim params = New CompilerParameters()
params.GenerateInMemory = True
params.ReferencedAssemblies.Add(Assembly.GetEntryAssembly().Location)
params.OutputAssembly = "OutputAssembly"
Dim code =
$"
Imports System
Imports System.Collections.Generic
Namespace {ns}
Partial Public Class DictionaryClass
Public {strName} As New Dictionary(Of String, String)
End Class
End Namespace"
Dim results = provider.CompileAssemblyFromSource(params, {code})
Dim assy = results.CompiledAssembly
Dim o As Object = assy.CreateInstance($"{ns}.DictionaryClass")
Me.dictionaryInstance = o
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
dictionaryInstance.carrot.Add("a", "b")
End Sub
End Class

Passing data from one form to another form's textboxes

I am trying to pass the selected nodes from a treeview to another form that is displayed in the text boxes.
this is my code in TreeView1_NodeMouseDoubleClick event
the code works fine when the data from the selected treeview is shown in the same form, but the problem is when I want to pass it to the other form 4 nothing is shown and the debug shows me that if it receives the values ​​but they are not reflected, maybe my code to refer to the other form is wrong I would like a support with this case.
Private Sub TreeView1_NodeMouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles TreeView1.NodeMouseDoubleClick
Dim nodeKey As String = TryCast(e.Node.Tag, String)
Dim form4 As New Form4
' Dim nodetext As String = TryCast(e.Node.Tag, String)
'Dim nodeKey As String = DirectCast(e.Node.Tag, String)
If nodeKey IsNot Nothing AndAlso nodeKey.StartsWith("DIST") Then
'You have double clicked a district node
Dim IDDISTRITO As Integer = Integer.Parse(nodeKey.Substring(4))
form4.lblco.Text = IDDISTRITO
'Do something with the district id here
'...
form4.txtdis.Text = e.Node.Text
form4.txtpro.Text = e.Node.Parent.Text
form4.txtdepa.Text = e.Node.Parent.Parent.Text
End If
End Sub
so I call form 3 where is the treeview
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim for3 As New Form3
for3.Show()
End Sub
As you assumed, yes you are referencing the forms incorrectly. Please follow this technique. In form3 class, declare a public variable Public Dim form4 As New Form4.
Then modify the form3 calling procedure like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim for3 As New Form3
for3.form4 = Me
for3.Show()
End Sub
Now modify your existing code to this :
Private Sub TreeView1_NodeMouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles TreeView1.NodeMouseDoubleClick
Dim nodeKey As String = TryCast(e.Node.Tag, String)
' Dim nodetext As String = TryCast(e.Node.Tag, String)
'Dim nodeKey As String = DirectCast(e.Node.Tag, String)
If nodeKey IsNot Nothing AndAlso nodeKey.StartsWith("DIST") Then
'You have double clicked a district node
Dim IDDISTRITO As Integer = Integer.Parse(nodeKey.Substring(4))
form4.lblco.Text = IDDISTRITO
'Do something with the district id here
'...
form4.txtdis.Text = e.Node.Text
form4.txtpro.Text = e.Node.Parent.Text
form4.txtdepa.Text = e.Node.Parent.Parent.Text
End If
End Sub
I have not tested the above code, but I believe you have got the idea.
Well I managed to solve it, the simplest thing was complicated, I publish the solution.
form 4 by calling 3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim for3 As New Form3
AddOwnedForm(for3)
for3.ShowDialog()
End Sub
just add this code and voila
Dim form4 As Form4 = CType(Owner, Form4)

How change Compare Multiple Textbox

I have 2 codes to change the color to Textbox, and unfortunately none of them work. What's wrong here? Why the code is not good. Every time I try the code, not worked, The first code changes the color to Textbox if there is a value between 1 and 7, and the second changes the value in ascending order from the lowest to the highest and assigns a corresponding color. Please tell me if these 2 codes are written correctly, or there is a write error.
Code 1: Image: http://www.imagebam.com/image/5ac5ee1073004874
Public Class TextBoxColors
Private ColorTable As Dictionary(Of String, Color) = New Dictionary(Of String, Color)()
Public Sub New()
ColorTable.Add("1", Color.Red)
ColorTable.Add("2", Color.Aqua)
ColorTable.Add("3", Color.Chocolate)
ColorTable.Add("4", Color.BlanchedAlmond)
ColorTable.Add("5", Color.BurlyWood)
ColorTable.Add("6", Color.BlueViolet)
ColorTable.Add("7", Color.DarkBlue)
End Sub
Public Function GetColor(ColorMap As String) As Color
Return If(ColorTable.Keys.Contains(ColorMap), ColorTable(ColorMap), Color.White)
End Function
End Class
Private txtColor As TextBoxColors = New TextBoxColors()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each txtDraw As TextBox In Me.Controls.OfType(Of TextBox).Where(Function(txt) txt.Name.StartsWith("txtDraw"))
AddHandler txtDraw.TextChanged,
Sub()
If Not String.IsNullOrEmpty(txtDraw.Text) Then
txtDraw.BackColor = txtColor.GetColor(txtDraw.Text)
End If
End Sub
Next
End Sub
Code 2: This 2nd code must be changed based on my text box, which starts with SumtxtDraw
- Image: http://www.imagebam.com/image/92a4091073004904
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FillColorList()
End Sub
Private Sub ColorTextBoxes()
FillTextBoxList(16, 23)
Dim SortedList As List(Of TextBox) = SortList()
Dim index As Integer
For Each txt As TextBox In SortedList
txt.BackColor = lstColor(index)
index += 1
Next
End Sub
Private Sub FillColorList()
lstColor.Add(Color.Red) 'for lowest number
lstColor.Add(Color.BlanchedAlmond)
lstColor.Add(Color.PaleGreen)
lstColor.Add(Color.Chartreuse)
lstColor.Add(Color.CadetBlue)
lstColor.Add(Color.Orange)
lstColor.Add(Color.DarkMagenta)
lstColor.Add(Color.Violet) 'for highest number
End Sub
Private Sub FillTextBoxList(StartNumber As Integer, EndNumber As Integer)
lstTextBox.Clear()
For suffix = StartNumber To EndNumber
lstTextBox.Add(DirectCast(Controls("TextBox" & suffix.ToString), TextBox))
Next
End Sub
Private Function SortList() As List(Of TextBox)
Dim orderedList = From txt In lstTextBox Order By CInt(txt.Text) Descending Select txt '$"{scorer.Score} - {scorer.Name}"
Dim SortedList As List(Of TextBox) = orderedList.ToList
Return SortedList
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ColorTextBoxes()
End Sub

How to populate ListBox from Dictionary Values?

Net
I am attempting to create a function that will allow a user to input text into a RTB and if that text exists in a Dictionary as a Key then a listbox is populated by all the values of the dictionary whose key they are related to , each value populates the listbox in a new line.
the 1st line is highlighted and the user can press the enter button and replace the text in the RTB with the highlighted text .
I'm new to VB so I do not know much .
this is what I have so far.
Public Class Oxnay
Private Sub Oxnay_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Tsort()
End Sub
Private TDictionary As Dictionary(Of String, String())
Public Sub Tsort()
TDictionary = New Dictionary(Of String, String())
TDictionary.Add("ape", {"pl", "tz", "xu"})
TDictionary.Add("lor", {"tv", "px"})
End Sub
Private Sub RichtextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
Dim lastword As String = RichTextBox1.Text.Split(" ").Last
If RichTextBox1.ContainsKey(lastword) Then
'display each string of the dictionary array related to lastword in different lines
'highlight first line
'Some[Code]
Else
ListBox1.Text = ""
End If
End Sub
End Class
For the first "lookup" part, try something like:
Private Sub RichtextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
Dim lastword As String = RichTextBox1.Text.Trim.Split(" ").Last
ListBox1.Items.Clear()
If Not IsNothing(TDictionary) AndAlso TDictionary.ContainsKey(lastword) Then
ListBox1.Items.AddRange(TDictionary(lastword))
End If
End Sub
Then to replace the currently selected text with the selection from the ListBox:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If ListBox1.SelectedIndex <> -1 Then
If RichTextBox1.SelectedText <> "" Then
RichTextBox1.SelectedText = ListBox1.SelectedItem.ToString
End If
End If
End Sub

How do you read a file and display in listbox in VB.NET?

I was trying to display data from file in a list saved on the hard drive by clicking on a button, however I'm not sure on haw to do it properly:
Private Sub btnListRecipes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListRecipes.Click
Dim TextLine As String
If System.IO.File.Exists(Filename) = True Then
Dim RecipeReader As New System.IO.StreamReader(Filename)
Do While RecipeReader.Peek() <> -1
TextLine = TextLine & RecipeReader.ReadLine() & vbNewLine
Loop
lstRecipes.Text = TextLine.Text
Else
MsgBox("File Does Not Exist")
End If
End Sub
I would be really grateful for assistance :D
Private Sub btnListRecipes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListRecipes.Click
Try
lstRecipes.AddRange(File.ReadAllLines(FileName))
Catch
MsgBox("Unable to read file")
End Try
End Sub
Use:
lstRecipes.Items.Add(TextLine.Text)
More specifically before it jumps to the next item in the list, so this would go right after your assignment of TextLine.
you can do this:
Imports System
Imports System.IO
Public Class Form1
Public Shared listTXT, listOfTxt, listOfTxtFile As New List(Of String)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim path As String = "C:\myDirectory\"
Dim parentinfo As New DirectoryInfo(path)
' Store Text file name in a list
For Each txtFile As FileSystemInfo In parentinfo.GetFileSystemInfos()
listTXT.Add(txtFile.Name)
Next
' Store Path of Text file in a list
For noOfTxtFile = 0 To listTXT.Count - 1
Dim pathOfFile As String = path & listTXT(noOfTxtFile)
listOfTxtFile.Add(pathOfFile)
Dim obj As System.IO.StreamReader
obj = System.IO.File.OpenText(pathOfFile)
While Not obj.EndOfStream
listOfTxt.Add(obj.ReadLine)
End While
Next
Dim lineOfTxt As Integer
Dim txt As String
For lineOfTxt = 0 To listOfTxt.Count - 1
txt = listOfTxt(lineOfTxt)
ListBox1.Items.Add(txt)
Next
End Sub
End Class