简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM