views:

1858

answers:

2

I wasn't able to find an answer anywhere about this seemingly simple topic: is it possible to align text of a single subitem in a WinForms ListView control?

If so, how?

I would like to have text in the same column aligned differently.

+1  A: 

The "ColumnHeader" class has a "TextAlign" property that will change the alignment for all subitems in the column. If you need something more fancy you could always use the "DrawSubItem" event and make it owner drawn.

David
Yes, I would need something more fancy, and that's what I was trying to imply by "single subitem" and "text in the same column aligned differently".I'll have a look at the "DrawSubItem" event.
Fueled
I cannot make your answer as the accepted one, because I feel my question hasn't been read properly and you did not provide any code samples.But, since it pointed me in the right direction, I voted you up. Thanks!
Fueled
A: 

For future reference, here's how I solved it:

// Make owner-drawn to be able to give different alignments to single subitems
lvResult.OwnerDraw = true;
...

// Handle DrawSubItem event
private void lvResult_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
    // This is the default text alignment
    TextFormatFlags flags = TextFormatFlags.Left;

    // Align text on the right for the subitems after row 11 in the 
    // first column
    if (e.ColumnIndex == 0 && e.Item.Index > 11)
    {
        flags = TextFormatFlags.Right;
    }

    e.DrawText(flags);
}

// Handle DrawColumnHeader event
private void lvResult_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
    // Draw the column header normally
    e.DrawDefault = true;
    e.DrawBackground();
    e.DrawText();
}

It was necessary to handle the DrawColumnHeader, otherwise no text or column separators would be drawn.

Fueled