Search code examples
arraysvb.netlistboxselectedindex

Using two arrays for output


I am trying to figure out how to output results based on a selection in a listbox object. Like if I select "2002", I want it to output the total rainfall for that year. I've tried researching through stack and google and I can't seem to find anything unless I am explaining it incorrectly. I want the arrays to output based on their indexes. Here's the necessary code.

Public Class frmRainfall

    ' Class level Variables

    Dim strYearSelection() As String = {
        "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009",
        "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017"
    }

    Dim strYear As String

    ' Yearly stats found online due to issues finding text file

    Dim decYearlyRainfallTotals() As Decimal = {

        28.66, 37.56, 31.36, 41.78, 31.1, 35.44, 48.82, 38.95, 30.73, 38.44, 46.99,
        36.39, 48.26, 32.56, 48.5, 44.83, 45.18, 47.87
    }

    Dim intOneYearTotal As Integer
    Dim intOverallTotal As Integer
    Dim intAverage As Integer

    Private Sub frmRainfall_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        'The Form at load will read the text file (Unavailable, read comment
        ' at the end of the frmRainfall sub procedure) and fill the ListBox object with the
        'Year items.

        For Each strYear In strYearSelection
            lstSelectYear.Items.Add(strYear)
        Next
    End Sub

Solution

  • This is what you want

    First, gets you the selected year

    Dim selectedYr as String = Convert.ToString(lstSelectYear.Text)
    

    Gets the index of the selected year and the precip in that index.

    Dim precip as Decimal = Convert.ToDecimal(decYearlyRainfallTotals(Array.IndexOf(strYearSelection, selectedYr)))
    

    I'd like to recommend a different data structure. A dictionary of key value pairs. It gives you a relationship between your months and precip amounts.

    Dim dict as new Dictionary(Of String, String)
    

    Adding a record:

    dict.Add("2000", 28.66)
    

    Getting all the years

    Dim allYears() as String = dict.Keys.ToArray()
    

    Getting a year's value

    Dim value as String = dict("2000")