Set tab positions inside a ListBox or TextBox in C#
This example demonstrates three methods for aligning values in columns.
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 function 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.Unfortunately I don't know of a .NET-ish only way to set tab stops inside a TextBox. To do this, use the SendMessage API function to send the TextBox the EM_SETTABSTOPS message. The SetTextBoxTabs function shown in the following code does this for you. Pass it a ListBox and an array of tab values.
private void SetListBoxTabs(ListBox lst, IListtabs)
{
// 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);
}
}
The final method 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 see a ListBox and two TextBoxes demonstrating these techniques.
using System.Runtime.InteropServices;
...
[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);
}


This article helped me set tabs in a textbox. Since there is no NETish way of doing it I was saved many days work.
It was extrememly useful and clear to follow. Thank you Rod Stevens.
Reply to this