Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all! Tell me how to add a button to an item Listbox?
Posted
Comments
bbirajdar 13-Jun-12 9:11am    
You need to create a custom listbox control

1 solution

Hi,

If you are using winform it will be a bit tricky. Here is a simple way to do it.
you need to draw a fake button in the DrawItem event and the click event.

C#
private void InitializeListBox()
{
    listBox1.Items.AddRange(new Object[] { "item 1", "item 2", "item 3", "item 4", "item 5", "item 6", "item 7", "item 8", "item 9" });
    listBox1.DrawMode = DrawMode.OwnerDrawFixed;
    listBox1.DrawItem += new DrawItemEventHandler(ListBox1_DrawItem);
    listBox1.ItemHeight = 25;
}

private void ListBox1_DrawItem(object sender,
    System.Windows.Forms.DrawItemEventArgs e)
{
    // draw a fake button, add some padding, and put a label.
    var bounds = e.Bounds;
    var buttonBounds = new Rectangle(bounds.X +2 , bounds.Y + 2, bounds.Width - 4, bounds.Height - 4);
    ControlPaint.DrawButton(e.Graphics, buttonBounds, ButtonState.Normal);
    _font = e.Font;

    var textBounds = new Rectangle(buttonBounds.X + 2, buttonBounds.Y + 2, buttonBounds.Width - 4, buttonBounds.Height - 4);
    e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), _font, Brushes.Black, textBounds, StringFormat.GenericDefault);
}

private Font _font;

private void listBox1_MouseClick(object sender, MouseEventArgs e)
{
    // draw a button pushed, wait a bit draw a button up.
    int index = this.listBox1.IndexFromPoint(e.Location);
    Rectangle bounds = this.listBox1.GetItemRectangle(index);

    var buttonBounds = new Rectangle(bounds.X + 2, bounds.Y + 2, bounds.Width - 4, bounds.Height - 4);
    ControlPaint.DrawButton(Graphics.FromHwnd(this.listBox1.Handle), buttonBounds, ButtonState.Pushed);

    var textBounds = new Rectangle(buttonBounds.X + 2, buttonBounds.Y + 2, buttonBounds.Width - 4, buttonBounds.Height - 4);
    Graphics.FromHwnd(this.listBox1.Handle).DrawString(listBox1.Items[index].ToString(),_font, Brushes.Black, textBounds, StringFormat.GenericDefault);

    Thread.Sleep(100);

    ControlPaint.DrawButton(Graphics.FromHwnd(this.listBox1.Handle), buttonBounds, ButtonState.Normal);
    Graphics.FromHwnd(this.listBox1.Handle).DrawString(listBox1.Items[index].ToString(), _font, Brushes.Black, textBounds, StringFormat.GenericDefault);

    // do what ever you want.
    if (index != System.Windows.Forms.ListBox.NoMatches)
    {
        MessageBox.Show(index.ToString());
    }
}


This code is a bit rough, you will need to polish it, but it gives you an idea.

Hope it helps.

Valery.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900