有一种简单的方法可以在弹出文本窗口中创建两列吗?

这似乎很容易做到。 我只是想弹出一个文本窗口并显示两列数据 – 左侧的描述和右侧显示的相应值。 我没有使用Forms很多,所以我只是抓住了第一个看起来合适的控件,一个TextBox。 我认为使用制表符将是创建第二列的简单方法,但我发现事情并没有那么好用。

我尝试这样做的方式似乎有两个问题(见下文)。 首先,我在很多网站上看到,由于字体的复杂程度,以及字符串问题等等,MeasureString函数不是很精确。 第二个是我不知道TextBox控件正在使用什么作为其下面的StringFormat。

无论如何,结果是我总是以一个选项卡关闭右栏中的项目。 我想我可以滚动自己的文本窗口并自己做所有事情,但是,哎呀,这不是一个简单的方法吗?

谢谢你的帮助!

TextBox textBox = new TextBox(); textBox.Font = new Font("Calibri", 11); textBox.Dock = DockStyle.Fill; textBox.Multiline = true; textBox.WordWrap = false; textBox.ScrollBars = ScrollBars.Vertical; Form form = new Form(); form.Text = "Recipe"; form.Size = new Size(400, 600); form.FormBorderStyle = FormBorderStyle.Sizable; form.StartPosition = FormStartPosition.CenterScreen; form.Controls.Add(textBox); Graphics g = form.CreateGraphics(); float targetWidth = 230; foreach (PropertyInfo property in properties) { string text = String.Format("{0}:\t", Description); while (g.MeasureString(text,textBox.Font).Width < targetWidth) text += "\t"; textBox.AppendText(text + value.ToString() + "\n"); } g.Dispose(); form.ShowDialog(); 

如果需要,可以将此VB.Net代码翻译为C#。 这里的理论是您更改控件中选项卡的大小。

 Private Declare Function SendMessage _ Lib "user32" Alias "SendMessageA" _ (ByVal handle As IntPtr, ByVal wMsg As Integer, _ ByVal wParam As Integer, ByRef lParam As Integer) As Integer Private Sub SetTabStops(ByVal ctlTextBox As TextBox) Const EM_SETTABSTOPS As Integer = &HCBS Dim tabs() As Integer = {20, 40, 80} SendMessage(ctlTextBox.Handle, EM_SETTABSTOPS, _ tabs.Length, tabs(0)) End Sub 

我也为你转换了一个版本到C#。 在VS2005中测试并工作。

将此using语句添加到表单中:

 using System.Runtime.InteropServices; 

在课堂声明后把它放好:

  private const int EM_SETTABSTOPS = 0x00CB; [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, int[] lParam); 

如果要设置tabstops,请调用此方法:

  private void SetTabStops(TextBox ctlTextBox) { const int EM_SETTABSTOPS = 203; int[] tabs = { 100, 40, 80 }; SendMessage(textBox1.Handle, EM_SETTABSTOPS, tabs.Length, tabs); } 

要使用它,这就是我所做的一切:

  private void Form1_Load(object sender, EventArgs e) { SetTabStops(textBox1); textBox1.Text = "Hi\tWorld"; } 

谢谢马特,你的解决方案对我很有帮助。 这是我的代码版本……

 // This is a better way to pass in what tab stops I want... SetTabStops(textBox, new int[] { 12,120 }); // And the code for the SetTabsStops method itself... private const uint EM_SETTABSTOPS = 0x00CB; [DllImport("User32.dll")] private static extern uint SendMessage(IntPtr hWnd, uint wMsg, int wParam, int[] lParam); public static void SetTabStops(TextBox textBox, int[] tabs) { SendMessage(textBox.Handle, EM_SETTABSTOPS, tabs.Length, tabs); } 

如果你想要一些真正的表格,哈伦先生的回答是好的。 DataGridView将为您提供非常Excel电子表格类型的外观。

如果你只想要一个两列布局(类似于HTML的表),那么试试TableLayoutPanel。 它将为您提供所需的布局,并能够在每个表格单元格中使用标准控件。

我相信唯一的方法是做一些类似于你正在做的事情,但是使用固定的字体并用空格做你自己的填充,这样你就不必担心标签扩展了。

文本框是否允许HTML使用? 如果是这种情况,只需使用HTML将文本格式化为表格。 否则,尝试将文本添加到数据网格,然后将其添加到表单。