2017-07-15 35 views
0

我想從兩個文本框添加文本到一個數組使用循環,但我的代碼使用數據填充每個數組的位置,而不只是一個位置。如何在VB.NET中停止填充整個數組的循環?

我當前的代碼:

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

您正在循環。如果您只想更新一個項目,請不要循環。如果您正嘗試向集合中添加*,請使用列表而不是數組。 – LarsTech

+0

爲什麼你需要插入collfoldername.Text 21次? – jonathana

+0

這裏有兩個選項,第一個也是最簡單的是遵循@LarsTech的建議,並使用'List(Of T)'代替,並且每次需要添加時使用.Add。如果你必須使用一個數組,那麼你可以使用一個Static變量來記住你必須使用的下一個索引,並從那裏分配值,在每次添加操作後遞增索引。 – Fabulous

回答

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 
+0

謝謝你的回答! – S4mJDawes