How to Make Array Items As Separate Links in Link Label - arrays

I have a LinkLabel which is set up to receive some URLs that result from making a selection in a ComboBox. What I'm trying to accomplish is for the user to select a state from my combo, and then be able to click the individual links that appear in link label.
Having my links in array, what I'm getting is the array displays the links as "one whole" string, and I want them to separate links. Here's what I have:
Public arrAlabama(2) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Create array for Alabama and add items.
arrAlabama(0) = "http://www.rolltide.com/"
arrAlabama(1) = "http://www.crimsontidehoops.com/"
arrAlabama(2) = "http://centralalabamapride.org/"
End Sub
Private Sub cboSelectState_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSelectState.SelectedIndexChanged
' Populate the link label.
If cboSelectState.SelectedIndex = 0 Then
lnklblLinkbox.Text = arrAlabama(0) _
& vbNewLine & arrAlabama(1) _
& vbNewLine & arrAlabama(2)
End If
End Sub
I'll have about 3 other arrStateName type arrays, so my SelectedIndex will span from [0] to [3], and each array will contain 3 URL links.
So where am I going wrong here? If anyone can give me a boost in the right direction I would appreciate it. Some suggested using Dictionary data type, but I'm new to and when I tried test it out, I got frustrated because it doesn't seem to produce the results I want. Using the TKey and TValue throws me off, and I can never get all of my links to display in the box. I used Integer for my keys, and String for my values (links), but couldn't make it work. Some much needed guidance would be appreciated. Is what I'm trying to do possible, or should I be using some other control types?

Make a class object:
Public Class StateLinks
Public Property State As String
Public Property Links As New List(Of String)
Public Overrides Function ToString() As String
'tells the combobox what to display
Return State
Public Sub New(state As String)
Me.State = state
End Sub
End Class
Load some statesLinks into a List(OF T):
Private stateLinksList As New List(Of StateLinks)
Private Sub LoadMe() Handles Me.Load
Dim coState As New StateLinks("Colorado")
coState.Links.Add("some link")
stateLinksList.Add(coState)
' continue adding then bind them
cboSelectState.DataSource = stateLinksList
End Sub
Get the links from the selection:
Private cb_selectionChanged() Handles cboSelectState.SelectedIndexChanged
Dim state = TryCast(cb.SelectedItem, StateLinks)
If Not state Is Nothing
For Each link As String In state.Links
'each link now available
Next
End If

Add a RichTextBox and set Detect Urls = true, BorderStyle = None, Backcolor = color of form, if it is on form. The size should be large enough to hold the url's. Then
Private Sub cboSelectState_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSelectState.SelectedIndexChanged
'Populate RichTextBox1.
If cboSelectState.SelectedIndex = 0 Then
RichTextBox1.Text = arrAlabama(0) _
& vbNewLine & arrAlabama(1) _
& vbNewLine & arrAlabama(2)
End If
End Sub
In
Private Sub RichTextBox1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkClickedEventArgs) Handles RichTextBox1.LinkClicked
Dim txt As String = e.LinkText 'txt is the link you clicked
End Sub
valter

Related

(VB.NET) display the lower half of a textfile to a listbox

I have to make a application that organizes a list of runners and their teams. In the following text file, I have to remove the top half of the text file (the top half being the listed teams) and display only the bottom half (the runners)in a listbox item.
The Text file:
# School [School Code|School Name|Coach F-Name|Coach L-Name|AD F-Name|AD L Name]
WSHS|Worcester South High School|Glenn|Clauss|Bret|Zane
WDHS|Worcester Dorehty High School|Ellsworth|Quackenbush|Bert|Coco
WBCHS|Worcester Burncoat High School|Gail|Cain|Kevin|Kane
QRHS|Quabbin Regional High School|Bob|Desilets|Seth|Desilets
GHS|Gardner High School|Jack|Smith|George|Fanning
NBHS|North Brookfield High School|Hughe|Fitch|Richard|Carey
WHS|Winchendon High School|Bill|Nice|Sam|Adams
AUBHS|Auburn High School|Katie|Right|Alice|Wonderland
OXHS|Oxford High School|Mary|Cousin|Frank|Daughter
# Roster [Bib #|School Code|Runner's F-Name|Runner's L-Name]
101|WSHS|Sanora|Hibshman
102|WSHS|Bridgette|Moffitt
103|WSHS|Karine|Chunn
104|WSHS|Shanita|Wind
105|WSHS|Fernanda|Parsell
106|WSHS|Albertha|Baringer
107|WSHS|Carlee|Sowards
108|WDHS|Maisha|Kleis
109|WDHS|Lezlie|Berson
110|WDHS|Deane|Rocheleau
111|WDHS|Hang|Hodapp
112|WDHS|Zola|Dorrough
113|WDHS|Shalon|Mcmonigle
I have some code that reads each row from the text file as an array and uses boolean variables to determine where to end the text file. This worked with displaying only the teams, which I've managed to do. But I now need to do the opposite and display only the players, and I'm a bit stumped.
My Code:
Private Sub btnLoadTeams_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadTeam.Click
' This routine loads the lstTeam box from an ASCII .txt file
' # School [School Code | Name | Coach F-Name| Coach L-Name | AD F-Name | AD L-Name]
Dim strRow As String
Dim bolFoundCode As Boolean = False
Dim bolEndCode As Boolean = False
Dim bolFoundDup As Boolean = False
Dim intPosition As Integer
Dim intPosition2 As Integer
Dim strTeamCodeIn As String
Dim textIn As New StreamReader( _
New FileStream(txtFilePath.Text, FileMode.OpenOrCreate, FileAccess.Read))
' Clear Team listbox
lstTeam.Items.Clear()
btnDeleteRunner.Enabled = True
Do While textIn.Peek <> -1 And Not bolEndCode
Me.Refresh()
strRow = textIn.ReadLine.Trim
If Not bolFoundCode Then
If "# SCHOOL " = UCase(Mid(strRow, 1, 9)) Then
bolFoundCode = True
End If
Else
If Mid(strRow, 1, 2) <> "# " Then
For Each item As String In lstTeam.Items
intPosition = InStr(1, strRow, "|")
strTeamCodeIn = Mid(strRow, 1, intPosition - 1)
intPosition2 = InStr(1, item, strTeamCodeIn)
If intPosition2 > 0 Then
bolFoundDup = True
MsgBox("Found Duplicate School Code: " & strTeamCodeIn)
End If
Else
bolEndCode = True
Next
If Not bolFoundDup Then
lstTeam.Items.Add(strRow)
Else
lstTeam.Items.Add("DUPLICATE School Code: " & strRow)
lstTeam.Items.Add("Please correct input file and reload teams")
bolEndCode = True
End If
End If
End If
Loop
End Sub
Ive put bolEndCode = True in between the part that reads the mid section of the text file, but all Ive managed to display is the following in the listbox:
# Roster [Bib #|School Code|Runner's F-Name|Runner's L-Name]
Any help or hints on how I would display just the runners to my "lstPlayers" listbox would be greatly appreciated. I'm a beginner programmer and We've only just started learning about reading and writing arrays in my .NET class.
First I made 2 classes, one Runner and one School. These have the properties available in the text file. As part of the class I added a function that overrides .ToString. This is for he list boxes that call .ToString for display.
Next I made a function that reads all the data in the file. This is very simple with the File.ReadLines method.
Then I created 2 variables List(Of T) T stands for Type. Ours Types are Runner and School. I used List(Of T) instead of arrays because I don't have to worry about what the size of the list is. No ReDim Preserve, just keep adding items. The FillList method adds the data to the lists. First I had to find where the schools ended and the runners started. I used the Array.FindIndex method which is a bit different because the second parameter is a predicate. Check it out a bit. Now we know the indexes of the lines we want to use for each list and use a For...Next loop. In each loop an instance of the class is created and the properties set. Finally the new object is added to the the list.
Finally we fill the list boxes with a simple .AddRange and the lists.ToArray. Note that we are adding the entire object, properties and all. The neat thing is we can access the properties from the listbox items. Check out the SelectedIndexChanged event. You can do the same thing with the Runner list box.
Sorry, I couldn't just work with your code. I have all but forgotten the old vb6 methods. InStr, Mid etc. It is better when you can to use .net methods. It makes your code more portable when the boss says "Rewrite the whole application in C#"
Public Class Runner
Public Property BibNum As Integer
Public Property SchoolCode As String
Public Property FirstName As String
Public Property LastName As String
Public Overrides Function ToString() As String
'The listbox will call .ToString when we add a Runner object to determin what to display
Return $"{FirstName} {LastName}" 'or $"{LastName}, {FirstName}"
End Function
End Class
Public Class School
Public Property Code As String
Public Property Name As String
Public Property CoachFName As String
Public Property CoachLName As String
Public Property ADFName As String
Public Property ADLName As String
'The listbox will call .ToString when we add a School object to determin what to display
Public Overrides Function ToString() As String
Return Name
End Function
End Class
Private Runners As New List(Of Runner)
Private Schools As New List(Of School)
Private Function ReadData(path As String) As String()
Dim lines = File.ReadLines(path).ToArray
Return lines
End Function
Private Sub FillLists(data As String())
Dim location = Array.FindIndex(data, AddressOf FindRosterLine)
'The first line is the title so we don't start at zero
For index = 1 To location - 1
Dim SplitData = data(index).Split("|"c)
Dim Schl As New School
Schl.Code = SplitData(0)
Schl.Name = SplitData(1)
Schl.CoachFName = SplitData(2)
Schl.CoachLName = SplitData(3)
Schl.ADFName = SplitData(4)
Schl.ADLName = SplitData(5)
Schools.Add(Schl)
Next
For index = location + 1 To data.GetUpperBound(0)
Dim SplitData = data(index).Split("|"c)
Dim Run As New Runner
Run.BibNum = CInt(SplitData(0))
Run.SchoolCode = SplitData(1)
Run.FirstName = SplitData(2)
Run.LastName = SplitData(3)
Runners.Add(Run)
Next
End Sub
Private Function FindRosterLine(s As String) As Boolean
If s.Trim.StartsWith("# Roster") Then
Return True
Else
Return False
End If
End Function
Private Sub FillListBoxes()
Dim arrRunners As Runner() = Runners.ToArray
Dim arrSchools As School() = Schools.ToArray
ListBox1.Items.AddRange(arrSchools)
ListBox2.Items.AddRange(arrRunners)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim arrRunner = ReadData("Runners.txt")
FillLists(arrRunner)
FillListBoxes()
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim Schl = DirectCast(ListBox1.SelectedItem, School)
TextBox1.Text = Schl.CoachLName
TextBox2.Text = Schl.Code
End Sub

Displaying an array with unknown values into a lable box

I am new to coding with visual basic.
Recently, I was tasked by my professor to write a programme that allows the user to enter five words. The words then should be sorted and displayed in alphabetical order.
To do this I decided the best approach would be to use an array.
My thinking was that if I created a counter at the start, I can create a different value for each column of the array when a button is clicked.
If the array exceeds five I have a message box pop-up that resets the code (although I realise I will also have to clear the contents of the array).
My problem arises in displaying the array. I have looked for solutions online, and none have helped me as of yet.
I need to sort the array into alphabetical order and then display it in a label box (lbl_DisplayArray). As I do not know the values of the array, this has proved tricky.
My code is below:
Public Class Form1
Dim i As Integer = 0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Array(4) As String
Array(i) = txt_UserWords.Text
End Sub
Private Sub btn_Next_Click(sender As Object, e As EventArgs) Handles btn_Next.Click
i += 1
If i >= 5 Then
i = 0
MsgBox("Array Limit Exceeded. Code Reset")
txt_UserWords.Text = ""
End If
End Sub
Private Sub btn_Sort_Click(sender As Object, e As EventArgs) Handles btn_Sort.Click
lbl_DisplayArray.Text =
End Sub
End Class
You'd be better off using
private myList as new List(of String).
Then to sort them you just call the .Sort() method. Just call .Add(txt_userWords.Text) to add the new string and use .Count to see how many of them you have.
When you're adding them to the label you can use
lbl_DisplayArray.Text = String.Join(vbCrLf, myList)
You'll need the list of to be a member of the class instead of a local variable (as you have declared Array). This will keep it alive and allow you to access it in other methods.
---------- edit ----------
Public Class Form1
private myList as new List(of String)
Private Sub btn_Next_Click(sender As Object, e As EventArgs) Handles btn_Next.Click
If myList.Count >= 5 Then
myList.Clear
Else
myList.add(txt_UserWords.Text)
End If
txt_UserWords.Text = ""
End Sub
Private Sub btn_Sort_Click(sender As Object, e As EventArgs) Handles btn_Sort.Click
myList.Sort()
lbl_DisplayArray.Text = String.Join(vbcrlf, myList)
End Sub
End Class

Display value of selected array

I have a CSV file that is formatted as (name,number) on each line.
I'm creating an app that loads all names, index(0), into a listbox at form-load and when a name is selected the number, index(1), is displayed in a .textbox.
I start by filling an array and displaying index(0) in the box. No Prob. But when the selected text changes I have problems. If you cant tell I'm new to VB. If I could assign a var to the selected text I could use a while loop but I'm not sure how to assign that. Is there a better way to go about this? Below is my source. Any help would be great.
Public Class Form1
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each line As String In IO.File.ReadAllLines("MembershipPhone.txt")
Dim myData = line.Split(","c)
Dim mName = myData(0)
Dim mPhone = myData(1)
ListBox1.Items.Add(mName)
Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
For Each line As String In IO.File.ReadAllLines("MembershipPhone.txt")
Dim query = line.Split(","c)
Dim mName = query(0)
Dim mPhone = query(1)
TextBox2.Text = mPhone
Next
End Sub

VB.NET: DYNAMICALLY ADD ARRAY TO COMBOBOX

Does anyone know how to dynamically add an array to a bunch of comboboxes in VB.net? I could really use the help (I've been struggling with this all day). When I try to do it my way I get an error on form load.
My code:
Private Sub Form1_Load(ByVal sender as Object, ByVal e as EventArgs) Handles Me.Load
Dim MyArray() as String = {"a","b","c"}
For each ctl as ComboBox in Me.Controls
if ctl.tag = "yadda" then ctl.Items.AddRange(MyArray)
Next
End Sub
Error: "Unable to cast object of type '...Button' to type '...Combobox'."
I've tried so many variations to this code but I just can't get it to work. I will eventually have nearly a hundred similarly constructed comboboxes in my application, and I'd like to be able to programmatically initialize their items. Could someone please help?
Thanks,
Elias
This is the way to do it :
Public Class Form1
Function getControl(ByVal controlName As String) As Control
Dim numCtrls = Me.Controls.Count()
For I As Integer = 0 To numCtrls - 1
If Me.Controls.Item(I).Name = controlName Then
If TypeOf Me.Controls.Item(I) Is ComboBox Then
Return CType(Me.Controls(controlName), ComboBox)
End If
End If
Next
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myArray As Array = {"a", "b", "c"}
Dim myComboBox As ComboBox
For Each ctl As Control In Me.Controls
If TypeOf ctl Is ComboBox Then
If ctl.Tag = "yadda" Then
myComboBox = getControl(ctl.Name)
myComboBox.Items.AddRange(myArray)
End If
End If
Next
End Sub
End Class
You loop through all controls (buttons, combo, etc ...) then you check if it is the type you want (ComboBox) and do whatever you need.
Good luck !

WinForm DateTimePicker blues. Is it me?

I want to be able to accept a NULL date using the DateTimePicker control.
The "Checked" property appears to be intended to specify whether the control "holds a date" or now. However, when "unchecked", the date still appears, though it appears disabled. To me, this is distracting. If the intent of the unchecked checkbox is to indicate that there is no date value, why is there ANY date value disable or otherwise that appears in the textbox? It seems to me that if the control is unchecked, the textbox should be EMPTY and that seeing a dimmed date value when the user really wants "no value" is distracting.
If the user toggled the checkbox on, then I would like the ability to place a default value into the textbox.
I am considering creating a usercontrol that toggles between a dateTimePicker control and a textBox, but I hate to go through this trouble.
I tried looking a Telerik's DateTimePicker but trying to get decent null handling functionality out of that control seems worse. I'd love to see a working example of what one of you think is a user-friendly code example with either the std MS or Telerik DateTimePicker control that accepts null input.
I've looked at a few opensource controls, but every time they fix one issue, they introduce others.
EDIT:
See my answer below. It seems to work fine, now I just want to make it part of every DateTimePicker's behavior.
I had the same problem. Well, actually I'm smart enough to understand, but my users had a problem.
I solved by removing the checkbox, and adding 2 radio buttons. Looks something like this now:
(using pseudo UI)
O No value entered
O | 1/1/2010 |V|
The top radiobutton is checked when there is no value (null), the bottom one when there is a value. I do not hide, or disable the bottom control, and users seem to understand.
The downside is, that it takes a lot more space.
PS: Next thing users will complain about is using the scroll-wheel when a combo-box has focus.
Klugey, but it seems to get the job done. If the checkbox is not checked, assume a NULL value.
Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker1.ValueChanged
If DateTimePicker1.Checked Then
DateTimePicker1.Format = DateTimePickerFormat.Short 'Or whatever the original format was
Else
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = " "
End If
End Sub
OK, the next question...How do I roll this behavior into a subclassed DateTimePicker? What I want to do is to capture the original values of the Format and CustomFormat properties as set in the Properties window. But, this clearly isn't the way to do it.
Here's my feeble attempt:
Public Class NullableDateTimePicker
Inherits DateTimePicker
Private _OriginalFormat As DateTimePickerFormat
Private _OriginalCustomerFormat As String
Private Sub NullableDateTimePicker_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.ValueChanged
If Me.Checked Then
Me.Format = _OriginalFormat
Me.CustomFormat = _OriginalCustomerFormat
Else
Me.Format = DateTimePickerFormat.Custom
Me.CustomFormat = " "
End If
End Sub
Private Sub _DP_FormatChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Static Count As Integer
If Count = 0 Then
_OriginalFormat = Me.Format
_OriginalCustomerFormat = Me.CustomFormat
End If
Count += 1
End Sub
Public Sub New()
AddHandler MyBase.FormatChanged, AddressOf _DP_FormatChanged
End Sub
End Class
I realise this is many years after your initial question but here's a subclass of the Telerik RadDateTimePicker that does what you were asking for:
Imports Telerik.WinControls.UI
Public Class DateTimePickerWithNull
Inherits Telerik.WinControls.UI.RadDateTimePicker
Private ReadOnly _calendar As RadCalendar
Sub New()
Dim calendarBehavior As RadDateTimePickerCalendar = Me.DateTimePickerElement.GetCurrentBehavior()
calendarBehavior.DropDownMinSize = New Size(220, 150)
_calendar = calendarBehavior.Calendar
_calendar.ShowFooter = True
AddHandler _calendar.ClearButton.Click, AddressOf ClearButton_Click
AddHandler _calendar.TodayButton.Click, AddressOf TodayButton_Click
End Sub
Private Sub ClearButton_Click(sender As Object, e As EventArgs)
'Do this to put the calendar away
_calendar.SelectedDate = _calendar.FocusedDate
'Then clear
Me.SetToNullValue()
End Sub
Private Sub TodayButton_Click(sender As Object, e As EventArgs)
_calendar.SelectedDate = _calendar.FocusedDate
End Sub
End Class
To get the value of the picker:
If DateTimePicker1.Value.Date = DateTimePicker1.NullDate Then
Label1.Text = "Null"
Else
Label1.Text = DateTimePicker1.Value.ToLongDateString
End If
A bit tricky to get right. This looked good:
Imports System.ComponentModel
Public Class MyDateTimePicker
Inherits DateTimePicker
Implements ISupportInitialize
Public Sub New()
Me.ShowCheckBox = True
Me.NullDate = True
End Sub
Private CustomFormatBacking As String = ""
Private FormatBacking As DateTimePickerFormat = DateTimePickerFormat.Long
<DefaultValue(True)> _
<Bindable(True)> _
Public Property NullDate() As Boolean
Get
Return Not Me.Checked
End Get
Set(ByVal value As Boolean)
Me.Checked = Not value
End Set
End Property
<DefaultValue("")> _
<Localizable(True)> _
<RefreshProperties(RefreshProperties.Repaint)> _
Public Shadows Property CustomFormat() As String
Get
Return CustomFormatBacking
End Get
Set(ByVal value As String)
CustomFormatBacking = value
If DesignMode Or Not NullDate Then MyBase.CustomFormat = value
End Set
End Property
<RefreshProperties(RefreshProperties.Repaint)> _
Public Shadows Property Format() As DateTimePickerFormat
Get
Return FormatBacking
End Get
Set(ByVal value As DateTimePickerFormat)
FormatBacking = value
If DesignMode Or Not NullDate Then MyBase.Format = value
End Set
End Property
<DefaultValue(true)> _
<Bindable(True)> _
<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
Public Shadows Property Checked() As Boolean
Get
Return MyBase.Checked
End Get
Set(ByVal value As Boolean)
MyBase.Checked = value
End Set
End Property
Private Sub updateNullState()
If NullDate and Not DesignMode Then
MyBase.CustomFormat = " "
MyBase.Format = DateTimePickerFormat.Custom
Else
MyBase.CustomFormat = CustomFormatBacking
MyBase.Format = FormatBacking
End If
End Sub
Public Sub BeginInit() Implements System.ComponentModel.ISupportInitialize.BeginInit
End Sub
Public Sub EndInit() Implements System.ComponentModel.ISupportInitialize.EndInit
updateNullState()
End Sub
Protected Overrides Sub OnValueChanged(ByVal eventargs As System.EventArgs)
MyBase.OnValueChanged(eventargs)
updateNullState()
End Sub
End Class

Resources