2010-01-20 98 views
5

我正在使用visual studio 2008,VB9,我試圖編寫一個應用程序,該應用程序基本上對用戶輸入的一組數據執行計算。在計算過程中,我想在每個步驟顯示數據,並將其保留在GUI的顯示區域(不會被正在顯示的下一個數據覆蓋)。Visual Basic循環並一次顯示一行

例如:

UserInput = 1 

Do 

    UserInput += 1 

    OutputLabel.Text = "UserInput " & UserInput 

Loop Until UserInput = 5 

和輸出看起來像

UserInput 1 UserInput 2 UserInput 3 UserInput 4 UserInput 5

我想這一點,和其他環結構似乎無法讓事情正確。實際的應用程序有點複雜,但這個例子很適合用於邏輯目的。

歡迎任何提示,謝謝!

回答

3

這是一個簡單的版本:

Dim delimiter as String = "" 
For UserInput As Integer = 1 To 5 
    OutputLabel.Text &= String.Format("{0}UserInput {1}", delimiter, UserInput) 
    delimiter = " " 
Next 

但是,有兩個問題它和其他類似(包括到目前爲止給出的其他答案):

  1. 它創建了很多額外的字符串
  2. 由於它處於循環中,因此只有在完成所有處理之後,標籤才能處理任何繪畫事件以自行更新。

所以,你可能也只是做到這一點:

Dim sb As New StringBuilder() 
Dim delimiter As String = "" 
For UserInput As Integer = 1 To 5 
    sb.AppendFormat("{0}UserInput {1}", delimiter, UserInput) 
    delimiter = " " 
Next 
OutputLabel.Text = sb.ToString() 

如果你真的想要得到樂趣,你可以做這樣的事情(無需環路!):

OutputLabel.Text = Enumerable.Range(1, 5).Aggregate(Of String)("", Function(s, i) s & String.Format("UserInput {0} ", i)) 
+0

我不認爲我想要那麼多樂趣:)我會嘗試一些這些,看看他們是什麼樣子 – Jmichelsen 2010-01-20 04:26:43

+0

我最終在這裏做的非常類似於你的方式,謝謝你的幫助! – Jmichelsen 2010-01-21 02:58:26

3

您需要連接OutputLabel.Text中的值。

OutputLabel.Text &= "UserInput " & UserInput 

您還可能要在循環之前將其復位:OutputLabel.Text = ""

1

如果你需要一個迭代索引,你可以嘗試像下面這樣

For I As Integer = 1 To 5 
    If I > 1 Then OutputLabel.Text &= " " 
    OutputLabel.Text &= "UserInput " & I.ToString() 
End For 

如果在集合中有用戶輸入,最好使用ForEach循環來提供服務。

1

你需要在GUI中完成嗎?如果簡單地處理並撲滅行這樣的,也許你應該考慮一個控制檯應用程序,在這種情況下,它變得很容易,只需調用

Console.WriteLine("my string") 
+0

它需要在GUI中,我會嘗試一些這些方法,看看會發生什麼 – Jmichelsen 2010-01-20 04:26:01

1

我會使用一個更適當的控制,像RichTextBox的

Dim UserInput As Integer = 0 
    Const userDone As Integer = 5 

    RichTextBox1.Clear() 
    Do 

     RichTextBox1.AppendText(String.Format("User input {0:n0} ", UserInput)) 
     RichTextBox1.AppendText(Environment.NewLine) 
     RichTextBox1.Refresh() 'the data at each step 
     UserInput += 1 

    Loop Until UserInput = userDone 
1

所有這些方面的實際工作真的很好,但適合我的情況的一個最好的是這樣的:

Do 
    Dim OutputString as String 
    Application.DoEvents() 'to make things paint actively 
    UserInput += 1 
    OutputString = String.Format("{0}", UserInput) 
    ListBox.Items.Add(OutputString) 


Loop Until UserInput = 5 

我改變了一些事情,以一個列表框,但三編輯這個方法與文本框和標籤,一些調整,他們都工作得很好。感謝你的幫助!