简体   繁体   中英

Adding items from textbox to a list(of string)

I`m new to vb.net. Looking to find out how to add items into the list. At the moment,its only adding one item. I need it to save many items and must be able to display all items in another textbox. Please help!

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim patients As List(Of String) = New List(Of String)
        patients.Add(TextBox1.Text)

        TextBox2.Text = patients.Count
    End Sub
End Class

Every time you click the button a new copy of the list variable is created and, of course, it is initially empty. You add one item but that's the end of the game.
If you want to preserve the contents of the list, you need to move the List variable at the global class scope

Public Class Form1
    Dim patients As List(Of String) = New List(Of String)

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
         patients.Add(TextBox1.Text)
         TextBox2.Text = patients.Count

   End Sub
   .....
End Class

You need to declare and instantiate your list outside of Button Click:

Public Class Form1
    Dim patients As New List(Of String)

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        patients.Add(TextBox1.Text)

        TextBox2.Text = patients.Count
    End Sub
End Class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM