我有Windows窗體項目。 表單上有一個名爲txt的文本框。 任務是在textBox解析文本的兩列中寫入用戶的字符串。每列必須有左側對齊。 這裏的例子:Windows窗體TextBox Bug?
--------------------------
Parameters Values
height 36
width 72
length of trousers 32
--------------------------
每個值都必須站在另一個之下。顯然,我們需要一種方法,在每個參數之後輸入必要數量的空格。我已經開發了這種方法:
private string AddSpaces(string str)
{
const int MAX_WIDTH = 50;
// We've got a 50 symbols field to fill it with current parameter
// name and add necessary number of spaces.
StringBuilder strWithSpaces = new StringBuilder();
int numOfSpaces = MAX_WIDTH - str.Length;
for (int i = 0; i < numOfSpaces; i++)
{
strWithSpaces.Append(" ");
}
return strWithSpaces.ToString();
}
我曾嘗試使用以下字符串測試這種方法:
string report = Environment.NewLine + "-------------" + DateTime.Now +
"-------------" + Environment.NewLine +
"Вихідні дані:" + Environment.NewLine +
"a:" +
AddSpaces("a:") +
"1" +
Environment.NewLine +
"ab:" +
AddSpaces("ab:") +
"1" +
Environment.NewLine +
"abcdefg:"+
AddSpaces("abcdefg:") +
"1" +
Environment.NewLine;
,使
txt.Text += report;
後,我有一個意想不到的畫面:
之後,我試圖在文件中寫入測試字符串。這裏的結果:
在文件中的輸出中是正確的。文本框中的輸出是錯誤的。 TextBox出錯了。如何解決這個問題? 這裏是我的測試項目的代碼:
/*
Correct output looks like this:
a: 1
ab: 1
abcdefg: 1
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace spaces
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string report = Environment.NewLine + "-------------" + DateTime.Now +
"-------------" + Environment.NewLine +
"Вихідні дані:" + Environment.NewLine +
"a:" +
AddSpaces("a:") +
"1" +
Environment.NewLine +
"ab:" +
AddSpaces("ab:") +
"1" +
Environment.NewLine +
"abcdefg:" +
AddSpaces("abcdefg:") +
"1" +
Environment.NewLine;
txt.Text += report;
using (StreamWriter outfile =
new StreamWriter(@"D:\test.txt"))
{
outfile.Write(report);
}
}
private string AddSpaces(string str)
{
const int MAX_WIDTH = 50;
StringBuilder strWithSpaces = new StringBuilder();
int numOfSpaces = MAX_WIDTH - str.Length;
for (int i = 0; i < numOfSpaces; i++)
{
strWithSpaces.Append(" ");
}
return strWithSpaces.ToString();
}
}
}
非常感謝,您的解釋幫助了很多! – 2012-04-27 14:18:27