2

I'd like to have a ListBox control contain items that span multiple lines.

Essentially what I want is each item to span multiple lines and be selectable as one item. Is there a way to do this?

CPS
  • 531
  • 1
  • 9
  • 18
  • 2
    Use the DrawMode = OwnerDrawVariable and the DrawItem and MeasureItem events. Yes, you have to draw it yourself now. – LarsTech Aug 21 '13 at 15:00
  • http://stackoverflow.com/questions/1673963/multi-line-list-items-on-winforms-listview-control – Habib Aug 21 '13 at 15:00
  • This is a possible duplicate of http://stackoverflow.com/q/9532368/941243. – Chris Aug 21 '13 at 15:01
  • You may want to look at [my example](http://stackoverflow.com/questions/15532639/complex-ui-inside-listboxitem) of such a thing using newer .Net features. – Federico Berasategui Aug 21 '13 at 15:01

1 Answers1

7

As suggested by LarsTech in his comment, all the other comments lead to some kind of fully coded example which may confuse you. I made this demo with just some lines of code for you to follow and get started easily:

 listBox1.DrawMode = DrawMode.OwnerDrawVariable;
 //First add some items to your listBox1.Items     
 //MeasureItem event handler for your ListBox
 private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
 {
   if (e.Index == 2) e.ItemHeight = 50;//Set the Height of the item at index 2 to 50
 }
 //DrawItem event handler for your ListBox
 private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
 {
   e.DrawBackground();
   e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds);
 }

enter image description here

King King
  • 61,710
  • 16
  • 105
  • 130
  • This is great with the exception that it does not show how to bind the events to the listbox. I found an example here, which shows it. http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.measureitem.aspx – CPS Aug 21 '13 at 15:22
  • @CPS registering events is just a very beginning job, I thought you already knew that. – King King Aug 21 '13 at 15:33
  • I knew that they needed to be, but I did not know the names of the events I needed in particular. I included that link for completeness's sake so that anyone else with this issue will have a complete answer. – CPS Aug 21 '13 at 16:53
  • 1
    Just pointing it out for the benefit of other people: double-buffering a `ListBox` does not work properly when the `DrawMode` is set to either `OwnerDrawFixed` or `OwnerDrawVariable`. If that becomes a concern, making a sub-class of a `ListBox` and implementing the `OnPaint` method yourself seems to work around the issue. – Anthony Aug 21 '13 at 17:26