我正在尝试使用循环将两个文本框中的文本添加到数组中,但是我的代码用数据填充每个数组位置,而不仅仅是一个位置。
我目前的代码:
If collfoldername.Text = "" Or collfolderref.Text = "" Then
MsgBox("Please fill all fields!", MsgBoxStyle.Critical, "Error")
Else
For i As Integer = 0 To 20
FolderName(i) = collfoldername.Text
FolderReference(i) = collfoldername.Text
Next
collfoldername.Text = ""
collfolderref.Text = ""
collfoldername.Focus()
End If
有什么建议吗?
答案 0 :(得分:0)
你的循环是从输入中分配数组中的所有元素。
如果您只想设置阵列中的下一个可用插槽,请不要使用循环。相反,您需要使用变量来跟踪数组中的位置,并为每个方法调用增加一次变量:
Public Index As Integer
Public FolderName(20) As String
Public FolderReference(20) As String
Sub SetArrayValues()
If Not Index<FolderName.Length Then
MsgBox("Array Is Full", MsgBoxStyle.Critical, "Error")
Else If collfoldername.Text = "" Or collfolderref.Text = "" Then
MsgBox("Please fill all fields!", MsgBoxStyle.Critical, "Error")
Else
FolderName(Index) = collfoldername.Text
FolderReference(Index) = collfoldername.Text
collfoldername.Text = ""
collfolderref.Text = ""
Index +=1
collfoldername.Focus()
End If
End Sub
Public Sub Button1_Click(Sender As Object, E As EventArgs) Handles Button1.Click
SetArrayValues()
End Sub
如果您想要比阵列大小更多的项目需要调整阵列的大小:
Public Index As Integer
Public FolderName(20) As String
Public FolderReference(20) As String
Sub SetArrayValues()
If Not Index<FolderName.Length Then
ReDim Preserve FolderName(Index)
ReDim Preserve FolderNameReference(Index)
End If
If collfoldername.Text = "" Or collfolderref.Text = "" Then
MsgBox("Please fill all fields!", MsgBoxStyle.Critical, "Error")
Else
FolderName(Index) = collfoldername.Text
FolderReference(Index) = collfoldername.Text
collfoldername.Text = ""
collfolderref.Text = ""
Index +=1
collfoldername.Focus()
End If
End Sub
Public Sub Button1_Click(Sender As Object, E As EventArgs) Handles Button1.Click
SetArrayValues()
End Sub
另一种选择是使用Generic.List(Of T)
并根据需要添加值。使用这种方法,您不需要跟踪阵列中的位置。
Public FolderName As New Generic.List(Of String)
Public FolderReference As New Generic.List(Of String)
Sub AddValues()
If collfoldername.Text = "" Or collfolderref.Text = "" Then
MsgBox("Please fill all fields!", MsgBoxStyle.Critical, "Error")
Else
FolderName.Add(collfoldername.Text)
FolderReference.Add(collfoldername.Text)
collfoldername.Text = ""
collfolderref.Text = ""
collfoldername.Focus()
End If
End Sub
Public Sub Button1_Click(Sender As Object, E As EventArgs) Handles Button1.Click
AddValues()
End Sub