Vb.net Data is not being incremented and added to list

print your name 10 times using for loop in vb net
vb.net loop through collection
what are control statements in vb net
difference between for next and for each loop in vb net
vb net string in array
looping constructs in vb net
vb.net continue for
vb.net add to string array

I'm having an issue trying to create a program that takes user input for a text file's location containing medical records. The diseases and number of patients are being added to a list. I'm having an issue where my console is printing 0 for both the total of XX unique diseases and YYY patient encounters. I am not getting any errors, just not the correct output.

I believe my issue is in my processData() sub, however I am unsure why it's printing back 0. Also, how do I go about keeping track of duplicate diseases that are added to the list as I'm trying to add a counter next to each time the disease is seen.

Sample from Disease.txt

3710079 JUDITH CLOUTIER 2012-08-04 Spastic Colonitis

3680080 VIRGINIA ALMOND 2012-07-25 Chronic Phlegm

3660068 ELLEN ENGLEHARDT 2012-04-06 Whooping Cough

3810076 LILLIAN KEMMER 2014-07-04 Scurvy

3630055 TERESA BANASZAK 2012-06-15 Scurvy

Output:

There were a total of 0 unique diseases observed.

A total of 0 patient encounters were held

Main():

' Global variables
Dim inputFile As String
Dim patientCounter = 0
Dim diseaseList As New List(Of String)
Dim dateList As New List(Of Date)

Sub Main()

    Dim reportFile As String
    Dim yn As String

    Console.ForegroundColor = ConsoleColor.Yellow
    Console.BackgroundColor = ConsoleColor.Blue
    Console.Title = "Medical Practice Data Analysis Application"
    Console.Clear()

    Console.WriteLine("Please enter the path and name of the file to process:")
    inputFile = Console.ReadLine

    If (File.Exists(inputFile)) Then

        ' Call to processData sub if input file exists
        processData()

        Console.WriteLine(vbCrLf & "Processing Completed...")
        Console.WriteLine(vbCrLf & "Please enter the path and name of the report file to generate")

        reportFile = Console.ReadLine
        File.Create(reportFile).Dispose()

        If (File.Exists(reportFile)) Then
            Console.WriteLine(vbCrLf & "Report File Generation Completed...")
        Else
            ' Call to sub to end program if directory does not exist
            closeProgram()
        End If

        ' Get user input to see report
        Console.WriteLine(vbCrLf & "Would you like to see the report file [Y/n]")
        yn = Console.ReadLine

        ' If user inputs "y" or "Y" then print report
        ' Otherwise close the program
        If (yn = "y" OrElse "Y") Then
            printFile()
        Else
            closeProgram()
        End If

    Else

        ' Call to sub to end program if file does not exist
        closeProgram()

    End If

    Console.ReadLine()

End Sub

processData Sub():

Public Sub processData()

    Dim lines As String() = File.ReadAllLines(inputFile)
    Dim tab
    Dim dates
    Dim diseaseCounter = 0

    For Each line As String In lines
        tab = line.Split(vbTab)
        patientCounter += 1
        dates = Date.Parse(line(3))
        dateList.Add(dates)
        'diseaseList.Add(line(4))
        Dim disease As New disease(line(4))
        diseaseList.Add(disease.ToString)
        'diseaseList(line(4)).

        For Each value In diseaseList
            'If value.Equals(line(4)) Then disease.counter += 1
        Next

    Next

    Dim uniqueDiseases As String() = diseaseList.Distinct().ToArray

End Sub

Disease.class

Class disease

    Dim counter As Integer = 0
    Dim name As String = ""

    Sub New(newDisease As String)
        name = newDisease
        counter = 0
    End Sub

End Class

printFile()

Sub printFile()

    Dim muchoMedical As String = "MuchoMedical Health Center"
    Dim diseaseReport As String = "Disease Report For the Period " & "earliest_date" & " through " & "latest_date"

    Console.WriteLine(vbCrLf & muchoMedical.PadLeft(Console.WindowWidth / 2))
    Console.WriteLine(diseaseReport.PadLeft(Console.WindowWidth / 2))

    Console.WriteLine(vbCrLf & "There were a total of " & diseaseList.Count & " unique diseases observed")
    Console.WriteLine("A total of " & patientCounter & " patient encounters were held")

    Console.WriteLine(vbCrLf & "Relative Histogram of each disease")

    For Each disease As String In diseaseList
        Console.WriteLine(vbCrLf & disease & vbTab & " ")
    Next

End Sub

closeProgram()

Sub closeProgram()

    Console.WriteLine(vbCrLf & "File does not exist")
    Console.WriteLine("Press Enter to exit the program...")
    Console.ReadLine()

End Sub

You don't need a disease class, really, if the most complicated thing you are doing is counting disease occurrences (your disease class had no public members so I don't know what you were doing there anyway). You can simply do everything with a little LINQ.

' processing section
Dim lines = File.ReadAllLines(inputFile)
Dim splitLines = lines.Select(Function(l) l.Split({vbTab}, StringSplitOptions.RemoveEmptyEntries))
Dim diseaseGrouping = splitLines.GroupBy(Function(s) s(3))
Dim patients = splitLines.Select(Function(s) s(1))
Dim dates = splitLines.Select(Function(s) DateTime.Parse(s(2)))

' report section
Dim padAmount = CInt(Console.WindowWidth / 2)
Dim muchoMedical As String = "MuchoMedical Health Center"
Dim diseaseReport As String = $"Disease Report For the Period {dates.Min():d} through {dates.Max():d}"
Console.WriteLine()
Console.WriteLine(muchoMedical.PadLeft(padAmount))
Console.WriteLine(diseaseReport.PadLeft(padAmount))
Console.WriteLine()
Console.WriteLine($"There were a total of {diseaseGrouping.Count()} unique diseases observed.")
Console.WriteLine($"A total of {patients.Count()} patient encounters were held")
For Each diseaseAndCount In diseaseGrouping
    Console.WriteLine()
    Console.WriteLine($"{diseaseAndCount.Key}{vbTab}{diseaseAndCount.Count()}")
Next

I think your disease name is in index 3. You were looking at 4 originally. Maybe you have a tab between first and last name? Change it if I was wrong. This may apply to any or all of the indices.

Output:

MuchoMedical Health Center Disease Report For the Period 4/6/2012 through 7/4/2014 There were a total of 4 unique diseases observed. A total of 5 patient encounters were held Spastic Colonitis 1 Chronic Phlegm 1 Whooping Cough 1 Scurvy 2

[Solved] add incremented values into listbox, Change your for loop to this;. Hide Copy Code. for (int i = 0; i < k; i++) { SerialBox. Items.Add(j + i + 1); } Good luck, OI. Set ctl = Me!Colors ' Prompt user to verify they wish to add new value. If MsgBox("Value is not in list. Add it?", _ vbOKCancel) = vbOK Then ' Set Response argument to indicate that data ' is being added. Response = acDataErrAdded ' Add string in NewData argument to row source.

I think the main issue with your code as listed above is that in the processData sub you have:

For Each line As String In lines
        tab = line.Split(vbTab)
        patientCounter += 1
        dates = Date.Parse(line(3))
        dateList.Add(dates)
        'diseaseList.Add(line(4))
        Dim disease As New disease(line(4))
        diseaseList.Add(disease.ToString)
        'diseaseList(line(4)).

        For Each value In diseaseList
            'If value.Equals(line(4)) Then disease.counter += 1
        Next
Next

I think you more likely mean to use tab(3) and tab(4) instead of line(3) and line(4) etc. You split the line into the "tab" variable but then don't use it. While you could rewrite everything and handle it differently, if you want to go with what you've got, I think that's your core error.

VB.NET For Loop Examples (For Each), with a Step. With For Each, enumerate an array. VB.NET For Loop Examples (For Each). Use For to increment or decrement with a Step. With For We can optionally place an Exit For inside this loop for added control over iteration. Step 1: We We do not need to maintain the index (or mess it up) ourselves. Here: We� How to: Reflect Data Source Updates in a Windows Forms Control with the BindingSource. 03/30/2017; 6 minutes to read +9; In this article. When you use data-bound controls, you sometimes have to respond to changes in the data source when the data source does not raise list-changed events.

I liked your idea of a class. You can wrap up all your data in one list. I enhanced your class so it could contain all the data in the file. Public Properties are automatic properties that have Get, Set, and the Private fields that hold the data written by the compiler. I have added an Overrides of the .ToString because you were not getting the results you expected. We have the parameterized constructor like you have except expanded to include all the properties.

The magic comes in the Linq query. The d stands for an item in the diseaseList which is an instance of the Disease class. Then I added an order by clause which will produce the results in alphabetical order by DiseaseName which is a string. Grouping by the unique DiseaseName into a Group with Count.

Notice in the second For Each loop we have all the properties of the class available.

I happened to be in a Windows Forms app so I used Debug.Print. Just replace with Console.WriteLine. I leave to you the fancy formatting if you desire.

Public Class Disease
    Public Property Name As String
    Public Property DiagnosisDate As Date
    Public Property DiseaseName As String
    Public Property ID As Integer
    Public Sub New(PatientID As Integer, PatientName As String, dDate As Date, sDisease As String)
        ID = PatientID
        Name = PatientName
        DiagnosisDate = dDate
        DiseaseName = sDisease
    End Sub
    'If you don't override ToString you will get the fully qualified name of the class
    'You can return any combination of the Properties as long as the end
    'result is a string
    Public Overrides Function ToString() As String
        Return Name
    End Function
End Class

Public Sub processData()
    Dim lines As String() = File.ReadAllLines(inputFile)
    Dim diseaseList As New List(Of Disease)
    For Each line As String In lines
        'I was having trouble with the tabs so I changed it to a comma in the file
        '3710079,JUDITH CLOUTIER,2012-08-04,Spastic Colonitis
        'the small c following the "," tells the compiler that this is a Char
        Dim tab = line.Split(","c)
        Dim inputDate = Date.ParseExact(tab(2), "yyyy-MM-dd", CultureInfo.InvariantCulture)
        Dim Studentdisease As New Disease(CInt(tab(0)), tab(1), inputDate, tab(3))
        diseaseList.Add(Studentdisease)
    Next

    Dim diseaseGrouping = From d In diseaseList
                          Order By d.DiseaseName
                          Group By d.DiseaseName
                          Into Group, Count

    For Each diseaseAndCount In diseaseGrouping
        Debug.Print($"{diseaseAndCount.DiseaseName}    {diseaseAndCount.Count()} ")
        For Each d In diseaseAndCount.Group
            Debug.Print($"    {d.Name},    {d.DiagnosisDate.ToShortDateString}")
        Next
    Next

End Sub

Excel vba increment cell value by 1, Excel vba increment cell value by 1. are only weekdays. column A has about 85,000 list and column B has about 270,000. Cells(n, 1) Then MsgBox " Duplicate data in " & r. It's not a ton of thinking, but it doesn't really add any value. The "somewhere" just happens to be the counter variable again, which is on the left� Tags: VB.NET, add items, list in VB.NET, list methids. In this article I describe how to add items in list. 4665 List Methods The List class is a generic collection

Get last inserted id in oracle, NET - How To Search Values From SQL Server Database And Set It Into TextBox In Vb. Net EntityFramework, I am connecting to MySql database from my c# The problem is coming from not being able to execute an SQL statement and get I would like to know if there is way to get the rows that are added ( or inserted ) � I have the same problem using VB.NET. I have tryed all the samples above. But whatever I do. The DataGridView is not only showing the new data it ad's the existing rows with a new listing with the old rows included, when I start with 17 rows it showes 35 rows.

Statements, You can declare a variable to be of any elementary data type or of any object When the code containing a declaration statement runs, Visual Basic reserves Note that the initial value you specify in a declaration statement is not In addition to numeric values, the assignment operator can also assign� Yes, UserID is a primary key and i just want to add value to Name column not UserID. Bikash Prakash Dash 6-May-13 7:23am so it is not possible primary key field cant be NULL.

Visual Basic .NET programming: ByVal and ByRef, How to pass data by reference and by value in VB NET. You can make changes to the copy and the original will not be altered. Visual Studio hides ByVal from When we incremented the variable, only the copy got 1 added to it. The original� A Reference to a VB.NET namespace is a requirement and must be added to a project before the objects in the namespace can be used. (A set of references is automatically added for the different templates in Visual Studio or VB.NET Express. Click "Show All Files" in Solution Explorer to see what they are.) But the Imports statement is not a

Comments
  • So diseaseList has items in it and you're still getting diseaseList.Count = 0 ?
  • First thing's first, put this Option Strict On at the top of your code and fix the compile errors. These declarations for example Dim tab, Dim dates should be along the lines of Dim tab As IEnumerable(Of String), Dim dates As DateTime. Also Dim patientCounter = 0 should be Dim patientCounter As Integer = 0. The rest should have suggestions in Visual Studio.
  • The tabs won't render in the block quote. Please indicate where there are tabs in the file. The reason I ask is that you seem to expect date to be in index 3, and disease to be in index 4, but I would consider them in indices 2 and 3 respectively.