Click here to Skip to main content
13,736,403 members
Click here to Skip to main content
Add your own
alternative version


244 bookmarked
Posted 30 Dec 2004
Licenced CPOL

Embedding Controls in a ListView

, 30 Dec 2004
Rate this:
Please Sign up or sign in to vote.
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)


About the Author

Software Developer (Senior) 4voice AG
Germany Germany
No Biography provided

You may also be interested in...


Comments and Discussions

Questionwhy set Bounds property in the ListView's Paint event? Pin
flyingxu9-Mar-09 16:28
memberflyingxu9-Mar-09 16:28 
GeneralChanging BackColor/ForeColor Pin
mikesinfo8-Dec-08 20:15
membermikesinfo8-Dec-08 20:15 
QuestionDockStyle Pin
tdsuper23-Jun-08 3:41
membertdsuper23-Jun-08 3:41 
AnswerRe: DockStyle Pin
mav.northwind23-Jun-08 5:27
membermav.northwind23-Jun-08 5:27 
GeneralRe: DockStyle Pin
tdsuper23-Jun-08 17:09
membertdsuper23-Jun-08 17:09 
Questionhow to bind data with listview control Pin
jayandrath23-May-08 2:02
memberjayandrath23-May-08 2:02 
GeneralThanks Mav Pin
jchalfant30-Oct-07 3:49
memberjchalfant30-Oct-07 3:49 
GeneralSimple to use, helpful and reliable Pin
Marcus Deecke2-Sep-07 12:51
memberMarcus Deecke2-Sep-07 12:51 
GeneralBug with removing rows with controls Pin
KodjoSuprem30-Jul-07 13:34
memberKodjoSuprem30-Jul-07 13:34 
GeneralRe: Bug with removing rows with controls [modified] Pin
jiaju_cao2-Aug-07 18:01
memberjiaju_cao2-Aug-07 18:01 
GeneralRe: Bug with removing rows with controls Pin
jchalfant30-Oct-07 11:37
memberjchalfant30-Oct-07 11:37 
GeneralRe: Bug with removing rows with controls Pin
Master Gollom1-Oct-08 2:19
memberMaster Gollom1-Oct-08 2:19 
GeneralProblem with combobox Pin
Louis-Philippe Carignan11-Jul-07 2:09
memberLouis-Philippe Carignan11-Jul-07 2:09 
QuestionScrollBar problem. Pin
Gavrilovici Corneliu30-May-07 21:42
memberGavrilovici Corneliu30-May-07 21:42 
QuestionRe: ScrollBar problem. Pin
Marek Wyborski8-Oct-07 3:59
memberMarek Wyborski8-Oct-07 3:59 
AnswerRe: ScrollBar problem. Pin
Marek Wyborski8-Oct-07 21:54
memberMarek Wyborski8-Oct-07 21:54 
GeneralAwesome Pin
lambn1-Mar-07 17:12
memberlambn1-Mar-07 17:12 
GeneralVery nice. Just a few questions. [modified] Pin
Th3Pr0ph3t12-Feb-07 7:50
memberTh3Pr0ph3t12-Feb-07 7:50 
QuestionWhen changing one ComboBox all other cb r also changed Pin
travellermania17-Jan-07 3:28
membertravellermania17-Jan-07 3:28 
GeneralText inside the button Pin
oeriksen1-Jan-07 10:25
memberoeriksen1-Jan-07 10:25 
GeneralRe: Text inside the button Pin
oeriksen1-Jan-07 12:48
memberoeriksen1-Jan-07 12:48 
GeneralRe: Text inside the button Pin
mav.northwind1-Jan-07 22:55
membermav.northwind1-Jan-07 22:55 
GeneralListViewItem deletion/sorting Pin
Anand Eyunni19-Nov-06 11:45
memberAnand Eyunni19-Nov-06 11:45 
QuestionColumn Heather Font? Pin
JoanComasFdz13-Oct-06 2:59
memberJoanComasFdz13-Oct-06 2:59 
QuestionHow work to not Using WinApi32 for Embedding Controls? Pin
shiken3-Sep-06 19:34
membershiken3-Sep-06 19:34 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180920.1 | Last Updated 31 Dec 2004
Article Copyright 2004 by mav.northwind
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid