我有 Windows 窗体项目。 窗体上有一个文本框,叫做txt。 任务是将用户的字符串写入两列解析文本的文本框中。每列必须左对齐。 这是示例:
--------------------------
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;
我有一张意想不到的照片:
之后,我尝试在文件中写入测试字符串。结果如下:
文件中的输出是正确的。文本框中的输出是错误的。文本框出了点问题。如何解决这个问题? 这是我的测试项目的代码:
/*
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();
}
}
}
最佳答案
尝试将 TextBox 控件的字体更改为 Mono-Spaced 字体,例如 Courier New
。
看起来您的 TextBox 仍在使用默认字体 Microsoft Sans Serif
,每个字母的宽度都不同。
关于c# - Windows 窗体文本框错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10351548/