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.
private void SetListBoxTabs(ListBox lst, IList 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 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.


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);
}

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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

  • 4/3/2010 4:20 PM Brian K Daniels wrote:
    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
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.