I knew today’s online app would be a pain, because I more/less learned .net from playing around there are many things that I’ve skipped because I haven’t needed them. Array’s is one of those things, I know their a huge part of working with data but so far I’ve only had to read them, loop through them and send the data to the screen. Today changes that..
Today’s App had a few hurdles to jump over including:
- Pull a list of states from a SQL table each in the form of NC, SC, NY each record having different amounts of states.
- List each state only once in a drop down box which means separating all the states and then converting the state abbreviation to the state name.
- Sort the stares in alphabetical order
Pulling the data from the SQL database was easy, since each record could have 1 state to multiple states, I just pulled all records and created one long string for them.
The end product looked like: NY, NC, SC, NJ, NY, OR, GA, OH, OH…
Now I wanted to separate all the data to a nice list and put it into an array like:
To separate a string use the Split function:
Dim sep() As Char = "," Dim sArrStates() As String Dim sstates As String = "" sArrStates = sstates.Split(sep)
The sep() line we are setting the character where we want to separate each word. Then with the split command we’re telling the program to split the sstates string at each “,” and put this list into the sArrStates Array.
Now to convert the state abbreviation to the state name. Using the StringDictionary function.
Dim myCol As New StringDictionary() myCol.Add("AL", "AL-Alabama") myCol.Add("AK", "AK-Alaska") myCol.Add("AR", "AR-Arkansas") myCol.Add("AZ", "AZ-Arizona") .......
Before adding the state name lets put the states in alphabetical order.
Now in one big swoop, Lets loop through the array, see if the state is listed in our StringDictionary, have another temp array to list the states into (this allows us to search the new array and if the current state hasn’t been added yet, add it to the new array and add it to the drop down list, if it is already listed in the new array, skip it)
'loop through the states array For i = 0 To sArrStates99.Length - 1 'check to see if abbrv. is in state list If myCol.ContainsKey(Trim(sArrStates99(i))) Then 'copy the state name to a temp holding space TempState = myCol(Trim(sArrStates99(i))) 'checks to see if the state is in the second array Dim WordToFind As String = Trim(sArrStates99(i)) Dim WordIndex As Int16 = sDistinctStates.IndexOf(WordToFind) Dim j As Integer = 0 'If state isn't in the second array, add it to the second array ' and add the state name and abbrv. to the dropdownlist If WordIndex < 0 Then sDistinctStates.Insert(j, WordToFind) DropDownList1.Items.Add(New ListItem(Trim(TempState), WordToFind)) j = j + 1 End If End If Next