基本上,我該如何在文本框中編寫一個新行,並保留現有信息。如何在文本框中的新行上顯示循環結果?
如果我有一個循環,
For i As Integer = 1 To 10
Dim result = i
i = i + 1
textbox1.text = result
Next
這將在文本框中顯示 '10'。我想這是這樣的:
...
基本上,我該如何在文本框中編寫一個新行,並保留現有信息。如何在文本框中的新行上顯示循環結果?
如果我有一個循環,
For i As Integer = 1 To 10
Dim result = i
i = i + 1
textbox1.text = result
Next
這將在文本框中顯示 '10'。我想這是這樣的:
...
像這樣的東西應該工作:
For i As Integer = 1 To 10
if i = 1 then
textbox1.text = i
else
textbox1.text &= vbcrlf & i
end if
Next
首先,您的TextBox必須允許多行。這是可以從設計者或代碼設置的文本框控件的屬性。如果高度不夠大,您可能需要確保滾動條在那裏滾動。
如果要從代碼設置屬性,請在表單的Load事件中使用此代碼。現在
' Set the Multiline property to true.
textBox1.Multiline = True
' Add vertical scroll bars to the TextBox control.
textBox1.ScrollBars = ScrollBars.Vertical
' Change the height of the textbox so that it could accomodate the lines
TextBox1.Height = 120
,你的方法已經在這條線的一個主要問題:
textbox1.text = result
你編碼的方式,我的每一個新的價值,會覆蓋舊值。你想要做的是首先構造一個字符串,然後將整個字符串發送到TextBox控件。如果您使用Console.WriteLine方法,這不是必需的。
方法1種
Dim s as string
s=""
For i As Integer = 1 To 10
s = s & Environment.Newline & i.ToString() 'we use Environment.NewLine to force new line
Next i
textbox1.text = s
方法2
.NET提供了一個類來處理字符串的東西比以前更好的方式。它不會在你的案件重要,但它是處理串聯時,體積大和/或性能事項
Dim s as new System.Text.StringBuilder() 'Initialize stringbuilder instance
For i As Integer = 1 To 10
s.AppendLine (i.ToString()) 'We use stringbuilder to concat. and inser line feed
Next i
textbox1.text = s.ToString()
注意的有效途徑:如果您想雙排間距,那麼你需要添加一個換行符(使用& )以上述兩種方法。
Method2'textbox1.text = s'這不會編譯爲文本是一個字符串而不是一個stringbuilder。它應該是s.tostring ...也許是type-o? – Codexer
感謝您的評論。你是對的。 – NoChance