2

我是 vb.net 的新手。希望了解如何将项目添加到列表中。目前,它只添加了一项。我需要它来保存许多项目,并且必须能够在另一个文本框中显示所有项目。请帮忙!

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
4

2 回答 2

2

每次单击该按钮时,都会创建一个列表变量的新副本,当然,它最初是空的。您添加了一项,但这就​​是游戏的结束。
如果要保留列表的内容,则需要在全局类范围内移动 List 变量

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
于 2013-09-24T20:02:57.623 回答
1

您需要在 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
于 2013-09-24T20:02:10.997 回答