Click here to Skip to main content
15,443,631 members
Articles / Desktop Programming / Windows Forms
Posted 30 Dec 2004


248 bookmarked

Embedding Controls in a ListView

Rate me:
Please Sign up or sign in to vote.
4.82/5 (109 votes)
30 Dec 2004CPOL4 min read
How to use arbitrary controls in ListView cells.

Sample Image - ListViewEmbeddedControls.jpg


Recently, I stumbled across several requests in various news groups on how to embed controls within a ListView.

There are several owner-drawn ListView controls here on CP, but I wanted to try and bend the standard ListView to my will... ;)


When you're intending to embed a control in a ListView, you'll have to make sure it's positioned correctly all the time. This can become difficult in several ways:

  • The position and size of a ListViewSubItem can be modified in various ways (for example, resizing the ListView, scrolling, resizing ColumnHeaders, and so on).
  • The default implementation of ListView doesn't have any way to tell you the size and location of ListViewSubItems.
  • Columns can be reordered.
  • ListViewItems can be sorted.

The easiest way to ensure the correct position would be right where the painting occurs, so I decided to override the ListView's WndProc and listen for WM_PAINT as a trigger to calculate the controls' positions.

There may be other, more efficient ways, but then it's really hard to get all the cases in which a control has to be re-positioned. Besides, I didn't find performance problems with a reasonable number of embedded controls.

Obtaining a cell's position and size

That's a little tricky, as the standard ListView won't help you here. It does have a GetItemRect() method, but it only gives you information on the entire ListViewItem. No way to retrieve the bounds of a certain ListViewSubItem here.

Luckily, I've been confronted with the same problem in a previous article of mine (In-place editing of ListView subitems), so the necessary functions were available already.

Basically, I get the height and vertical position of the cell from GetItemRect() and calculate its horizontal position and width from the current ColumnHeaders.

To calculate the left margin of a cell, you just have to sum up the widths of all ColumnHeaders left of your cell, i.e., with indices smaller than your ListViewSubItem's index, right? Unfortunately, not. Columns can be reordered by the users and the ListView's Columns collection doesn't reflect these changes :(

So, I had to resort to interop to get the current display order for the columns. There's a message LVM_GETCOLUMNORDERARRAY the ListView understands to give you the current column order in the form of an int array:

/// <summary>
/// Retrieve the order in which columns appear
/// </summary>
/// <returns>Current display order of column indices</returns>
protected int[] GetColumnOrder()
  IntPtr lPar = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)) * Columns.Count);
  IntPtr res = SendMessage(Handle, LVM_GETCOLUMNORDERARRAY, 
               new IntPtr(Columns.Count), lPar);
  if (res.ToInt32() == 0) // Something went wrong
    return null;
  int [] order = new int[Columns.Count];
  Marshal.Copy(lPar, order, 0, Columns.Count);
  return order;

Once I had this array, I could simply sum up the widths of the columns displayed left of the cell in question.

Positioning the embedded control

That's the easiest part. Once I had the correct position and size of a ListViewSubItem, I only had to assign this information to the embedded control's Bounds property in the ListView's Paint event.

What about sorting?

My first tests didn't include sorting the ListView. My first tests also just held the row and column number of the embedded control as a reference to where to put the control.

The problem arose when I allowed the user to sort the ListView. All ListViewItems changed their position but none of the embedded controls did. What had happened?

When a ListView is sorted, the ListViewItems change their position in the Items collection. That's OK, but after sorting, they also have their Index property changed to reflect the current position in the collection and not the position at which they were added originally.

Luckily, this behavior could be fixed easily by adding a reference to the ListViewItem in question to my management structure. Now, I could retrieve the right display position of the ListViewItem as well.

Using the new ListView

To embed a given control in the new, extended ListView, you have two new methods:

public void AddEmbeddedControl(Control c, int col, int row);
public void AddEmbeddedControl(Control c, int col, int row, DockStyle dock);

The second function allows you to specify how the control is positioned and sized in its target cell. Usually, you'd use DockStyle.Fill to let the control use the entire SubItem rectangle (default value if you don't give the dock parameter). If you don't want your control to be resized in both directions, you can specify one of the other DockStyles. If you specify DockStyle.None, your control will not be resized at all and thus might overlap other parts of the ListView.

There are also methods to remove a given control or query the ListView for the control embedded at a certain position.

About the demo

I've added a little demo project so that you can try out the new ListView and its features.

While building the demo, I tried embedding a RichTextBox in the ListView and it worked quite nicely, but I was annoyed to find out that I couldn't keep the RichTextBox from being selected, so I've also included a ReadOnlyRichTextBox class to the demo.

I don't think this qualifies for a separate article, but you can use this ReadOnlyRichTextBox as well with your projects, when you want a label with pretty formatting.

Please feel free to comment on the article and don't forget to vote!

Release History

  • 31.12.2004 V1.0

    Initial release.


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

Written By
Software Developer (Senior) 4voice AG
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

GeneralMy vote of 5 Pin
Hermann Hehn5-Oct-21 22:44
MemberHermann Hehn5-Oct-21 22:44 
QuestionTrying to Swap Two Items Pin
Member 1207484930-May-17 7:11
MemberMember 1207484930-May-17 7:11 
BugThank you very much for an EXCELLENT resource Pin
Mark Millman14-Jan-16 18:08
MemberMark Millman14-Jan-16 18:08 
QuestionProblem with button clicking Pin
Member 115915208-Apr-15 10:46
MemberMember 115915208-Apr-15 10:46 
QuestionUse Theme Explorer??? Pin
Member 1145224915-Feb-15 1:32
MemberMember 1145224915-Feb-15 1:32 
QuestionNice job! Pin
Ravi Bhavnani14-Nov-14 4:50
professionalRavi Bhavnani14-Nov-14 4:50 
QuestionQuestion about ListView messages and Windows Messages Pin
brenntengel@yahoo.fr27-Jun-14 11:31
Memberbrenntengel@yahoo.fr27-Jun-14 11:31 
QuestionAmazing Pin
Brian Richardson23-Jun-14 6:25
MemberBrian Richardson23-Jun-14 6:25 
GeneralAusgezeichnet! Pin
toneware16-Oct-12 3:52
Membertoneware16-Oct-12 3:52 
QuestionJust awesome. Pin
pdoxtader21-Jun-12 4:57
professionalpdoxtader21-Jun-12 4:57 
GeneralMy vote of 4 Pin
faley21-Mar-12 0:26
Memberfaley21-Mar-12 0:26 
QuestionButton for each row? Pin
Marius Iulian Mihailescu7-Feb-12 10:22
professionalMarius Iulian Mihailescu7-Feb-12 10:22 
AnswerRe: Button for each row? Pin
faley21-Mar-12 0:35
Memberfaley21-Mar-12 0:35 
QuestionBug in Progress bar display Pin
YKK Reddy27-Dec-11 23:15
MemberYKK Reddy27-Dec-11 23:15 
AnswerRe: Bug in Progress bar display Pin
Stuartbaker428-Jan-13 13:41
MemberStuartbaker428-Jan-13 13:41 
QuestionGet ListViewItem from Click event Pin
crazyfool21000029-Sep-11 21:57
Membercrazyfool21000029-Sep-11 21:57 
QuestionHow do I change the height of the rows? Pin
peter_m_22-Sep-11 7:16
Memberpeter_m_22-Sep-11 7:16 
Generalexcellent post Pin
Yael018-Aug-10 13:08
MemberYael018-Aug-10 13:08 
GeneralSorting the progressbars Pin
Timotei_Younge21-Jun-10 1:05
MemberTimotei_Younge21-Jun-10 1:05 
Questionadding controls to datagridviews Pin
ymaod23-Mar-10 5:17
Memberymaod23-Mar-10 5:17 
GeneralMy vote of 1 Pin
Berry1418-Mar-10 4:12
MemberBerry1418-Mar-10 4:12 
GeneralHelp... embedded control is not highlighting the selected row Pin
Tien Pham22-Jul-09 5:55
MemberTien Pham22-Jul-09 5:55 Pin
mrcouthy11-Jun-09 1:19
Membermrcouthy11-Jun-09 1:19 
AnswerRe: Pin
Thomas ST4-Nov-09 1:22
MemberThomas ST4-Nov-09 1:22 
QuestionHow can I add multiple button control in a field? Pin
Md. Ali Naser Khan3-Jun-09 23:22
MemberMd. Ali Naser Khan3-Jun-09 23:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.