BP Forums
Using a string as an alias/nickname - Printable Version

+- BP Forums (https://bpforums.info)
+-- Forum: Programming Discussion (https://bpforums.info/forumdisplay.php?fid=34)
+--- Forum: VB.NET (https://bpforums.info/forumdisplay.php?fid=43)
+--- Thread: Using a string as an alias/nickname (/showthread.php?tid=906)



Using a string as an alias/nickname - strawman83 - 06-04-2015

So part of the application I am building is a user blog, where the user can submit new blog entries or view previous entries. I've managed to write to/read the blog entry to and from a text file, with a 9 digit date format in front of the entry.

The problem I am having is that when I am loading the previous entries into a comboBox, it is loading all the text from the blog into each item of the comboBox.

What I want to do is load the date of the blog into the comboBox only, and when the user clicks on said date the entire blog text file is loaded into a textBox.

In the code below, I really need the blogAlias string to act as alias/nickname in the comboBox for the actual blog text. But I can't figure out how to do it.

Code:
'Fill comboBox with array of previous blog entries

While j < blogLineCount

          blogAlias = blogArray(j).Substring(1,9)
          comboBox1.Items.Add(blogArray(j))
          j = j + 1


End While



RE: Using a string as an alias/nickname - brandonio21 - 06-20-2015

Hello strawman83,


I think that to resolve this issue you have two reasonable solutions.
1) Create a new ComboBoxItem object that has a "tag" field that contains the text of the blog post. That is, you can do something like this:

Code:
while j < blogLineCount
   blogAlias = blogArray(i).Substring(1,9)
    Dim item as New ComboBoxItem
    item.text = blogAlias
    item.tag = blogArray(i)
   combobox1.Items.Add(item)

Of course, this option is fairly complicated since you will need to make a custom version of the ComboBox object and a new ComboBoxItem class.

2) Make a List that mirrors the ComboBox. This is often the solution that I use to this problem since it is so simple. Your code will then look something like this:

Code:
Dim text as New List<String>()
while j < blogLineCount
    blogAlias = blogArray(i).Substring(1,9)
    comboBox1.Items.Add(blogAlias)
    text.Add(blogArray(i))


' This function is called when the user changes the ComboBox item
Private Sub Item_Changed(ByVal obj as Object, ByVal e as EventArgs) Handles comboBox1.SelectedIndexChanged
    TextBox1.Text = text.Item(comboBox1.SelectedIndex)
End
In this method, the indices of the blog text and the blog "aliases" are synced, so that when the user selects an alias, they are also selecting the index of the corresponding text. I hope this helps!