Dr. Rajesh Rolen
Dr. Rajesh Rolen

Reputation: 14285

How to make Listbox's texts center aligned in desktop application using c#.net

Please tell me how can I align center to my ListBox's text in desktop application.
I am using C#.Net in Visual Studio 2005.

I am using Windows forms.

Upvotes: 7

Views: 15917

Answers (3)

Nazarian
Nazarian

Reputation: 1

use TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter;

listBox1.DrawMode = DrawMode.OwnerDrawFixed;
listBox1.DrawItem += new DrawItemEventHandler(listBox1_OnDrawItem);

private void listBox1_OnDrawItem(object sender,DrawItemEventArgs e)
{
    TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter;
    if (e.Index >= 0)
    {
        e.DrawBackground();
        var textRect = e.Bounds;
        string itemText = DesignMode ? "Custom ListBox" : Items[e.Index].ToString();
        TextRenderer.DrawText(e.Graphics, itemText, e.Font, textRect, e.ForeColor, flags);
        e.DrawFocusRectangle();
    }
}

Upvotes: 0

C.Evenhuis
C.Evenhuis

Reputation: 26446

You can set the DrawMode property of the ListBox to DrawMode.OwnerDrawFixed, which gives you control over the entire graphical representation of each item. For instance:

ListBox listBox = new ListBox();
listBox.DrawMode = DrawMode.OwnerDrawFixed;
listBox.DrawItem += new DrawItemEventHandler(listBox_DrawItem);

    void listBox_DrawItem(object sender, DrawItemEventArgs e)
    {
        ListBox list = (ListBox)sender;
        if (e.Index > -1)
        {
            object item = list.Items[e.Index];
            e.DrawBackground();
            e.DrawFocusRectangle();
            Brush brush = new SolidBrush(e.ForeColor);
            SizeF size = e.Graphics.MeasureString(item.ToString(), e.Font);
            e.Graphics.DrawString(item.ToString(), e.Font, brush, e.Bounds.Left + (e.Bounds.Width / 2 - size.Width / 2), e.Bounds.Top + (e.Bounds.Height / 2 - size.Height / 2)); 
        }
    }

Upvotes: 10

Enrico Campidoglio
Enrico Campidoglio

Reputation: 59923

In WPF you'll use the Control.HorizontalContentAligment property:

<ListBox Name="lstSample" 
         HorizontalContentAlignment="Center"
    <ListBoxItem>Item 1</ListBoxItem>
    <ListBoxItem>Item 2</ListBoxItem>
    <ListBoxItem>Item 3</ListBoxItem>
</ListBox>

In Windows Forms you'll have to draw the content of the ListBox yourself by handling the DrawItem event. Here's an example on how to do it.

Upvotes: 1

Related Questions