Set tab positions inside a ListBox or TextBox in C#

tab positions

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 see a ListBox and two TextBoxes demonstrating these techniques.






This entry was posted in controls and tagged , , , , , , , , , , , , . Bookmark the permalink.

One Response to Set tab positions inside a ListBox or TextBox in C#

  1. Brian K Daniels says:

    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.

Leave a Reply

Your email address will not be published. Required fields are marked *