This seemed like an easy thing to do. I just wanted to pop up a text window and display two columns of data — a description on the left side and a corresponding value displayed on the right side. I haven’t worked with Forms much so I just grabbed the first control that seemed appropriate, a TextBox. I thought using tabs would be an easy way to create the second column, but I discovered things just don’t work that well.
There seems to be two problems with the way I tried to do this (see below). First, I read on numerous websites that the MeasureString function isn’t very precise due to how complex fonts are, with kerning issues and all. The second is that I have no idea what the TextBox control is using as its StringFormat underneath.
Anyway, the result is that I invariably end up with items in the right column that are off by a tab. I suppose I could roll my own text window and do everything myself, but gee, isn’t there a simple way to do this?
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();
If you want, you can translate this VB.Net code to C#. The theory here is that you change the size of a tab in the control.
I converted a version to C# for you, too. Tested and working in VS2005.
Add this using statement to your form:
Put this right after the class declaration:
Call this method when you want to set the tabstops:
To use it, here is all I did: