Title: Set tab positions inside a ListBox or TextBox in C#
This example demonstrates three methods for aligning values in columns, two of which set tab positions in a ListBox or TextBox.
To set tabs in a ListBox, you need to set the control's UseCustomTabOffsets property to true. Then get the control's CustomTabOffset collection and add your tabs to it.
The SetListBoxTabs method shown in the following code does all of this for you. Simply pass it a ListBox and a list or array of tab values.
// Set tab stops inside a ListBox.
private void SetListBoxTabs(ListBox lst, IEnumerable<int> tabs)
{
// Make sure the control will use them.
lst.UseTabStops = true;
lst.UseCustomTabOffsets = true;
// Get the control's tab offset collection.
ListBox.IntegerCollection offsets = lstCars.CustomTabOffsets;
// Define the tabs.
foreach (int tab in tabs)
{
offsets.Add(tab);
}
}
Unfortunately I don't know of a .NET-ish way to set tab stops inside a TextBox. To do this, you can use the SendMessage API function to send the TextBox the EM_SETTABSTOPS message. The SetTextBoxTabs method shown in the following code does this for you. Pass it a TextBox and an array of tab values.
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg,
Int32 wParam, int[] lParam);
private const uint EM_SETTABSTOPS = 0xCB;
// Set tab stops inside a TextBox.
private void SetTextBoxTabs(TextBox txt, int[] tabs)
{
SendMessage(txt.Handle, EM_SETTABSTOPS, tabs.Length, tabs);
}
The final method for setting tabs is to make the ListBox or TextBox use a fixed width font such as Courier New. Then format the data so each field has the same length. This method has the advantage that you can format columns to align on the left or right. When you use tabs, columns always align on the left.
Download the example to experiment with it and to see additional details.
|