Click here to Skip to main content
Click here to Skip to main content

A data-bound multi-column combobox

, 27 Jul 2007 BSD
Rate this:
Please Sign up or sign in to vote.
An ownerdrawn multi-column combobox class with support for data-binding


I had to write a multi-column combobox at work that supported generic data binding, and I thought it might prove useful for others too. MultiColumnComboBox is a ComboBox derived class written entirely in C# and you can bind it to any data source that has multiple columns (though it doesn't matter if it only has a single column either). It also works in unbound mode though it doesn't make much sense to use it if you are not using data binding.

Class usage

Using the class is fairly straightforward. Once you have your data source you just need to set the DataSource property of the MultiColumnComboBox class. The control does not support the ComboBoxStyle.Simple style and in addition it will insist on DrawMode being set to OwnerDrawVariable. Exceptions are thrown so that you won't inadvertently attempt to break either of those limitations which is pretty handy because the Visual Studio property grid will not then let you change those values.

The class has been tested on Windows XP SP2 as well as on Windows Vista (Ultimate Edition) both from a Visual Studio design perspective as well as from a runtime perspective. Here are some examples of populating the control with various types of data sources. In this first example, we populate it using a DataTable.

// Populate using a DataTable

DataTable dataTable = new DataTable("Employees");

dataTable.Columns.Add("Employee ID", typeof(String));
dataTable.Columns.Add("Name", typeof(String));
dataTable.Columns.Add("Designation", typeof(String));

dataTable.Rows.Add(new String[] { "D1", "Natalia", "Developer" });
dataTable.Rows.Add(new String[] { "D2", "Jonathan", "Developer" });
dataTable.Rows.Add(new String[] { "D3", "Jake", "Developer" });
dataTable.Rows.Add(new String[] { "D4", "Abraham", "Developer" });
dataTable.Rows.Add(new String[] { "T1", "Mary", "Team Lead" });
dataTable.Rows.Add(new String[] { "PM1", "Calvin", "Project Manager" });
dataTable.Rows.Add(new String[] { "T2", "Sarah", "Team Lead" });
dataTable.Rows.Add(new String[] { "D12", "Monica", "Developer" });
dataTable.Rows.Add(new String[] { "D13", "Donna", "Developer" });

multiColumnComboBox1.DataSource = dataTable;
multiColumnComboBox1.DisplayMember = "Employee ID";
multiColumnComboBox1.ValueMember = "Name";

The DisplayMember property will dictate the value that's visible in the edit box part of the combobox. And the ValueMember property will dictate which of the columns will show up in bold. If you look at the screenshots, you can clearly see this in action. In the next example, we use an array of a custom type.

public class Student
    public Student(String name, int age)
    { = name;
        this.age = age;

    String name;

    public String Name
        get { return name; }

    int age;

    public int Age
        get { return age; }

// Populate using a collection

Student[] studentArray = new Student[] 
{ new Student("Andrew White", 10), new Student("Thomas Smith", 10), 
  new Student("Alice Brown", 11), new Student("Lana Jones", 10), 
  new Student("Jason Smith", 9), new Student("Amamda Williams", 11)

multiColumnComboBox2.DataSource = studentArray;
multiColumnComboBox2.DisplayMember = multiColumnComboBox2.ValueMember = "Name";

Notice how we've set both DisplayMember and ValueMember to the same column field - this is perfectly okay to do. By the way if you don't set the ValueMember it will use the first column by default. You must set the DisplayMember though, else you'll see some odd strings depending on how a specific type's ToString is implemented. I decided not to provide a default as it would most likely result in non-ideal columns getting displayed. I've used a drop-down list style combobox for my 3rd example and also used a List<> object - though by now it must be pretty obvious to anyone reading this that you can basically use any standard data source.

// Drop-down list (non-editable)

List<Student> studentList = new List<Student>(studentArray);

The main difference in using a drop-down list will be that you'll see the multiple columns even when the combobox is not dropped down. Note that those who want to prevent this behavior can check if DrawItemEventArgs.State has the ComboBoxEdit flag (in the OnDrawItem method) and change the behavior accordingly. For our purposes this behavior was pretty good and I personally thought it to be the more intuitive way to do it. And finally, you can use it without data-binding, though I can't think of any reason why you'd want to do that.

// Trying to use as a regular combobox

multiColumnComboBox4.SelectedIndex = 0;

Implementation details

One of the first things I did was to hide both the DrawMode and the DropDownStyle properties to prevent users from inadvertently setting unsupported values.

public new DrawMode DrawMode 
        return base.DrawMode;
        if (value != DrawMode.OwnerDrawVariable)
            throw new NotSupportedException("Needs to be DrawMode.OwnerDrawVariable");
        base.DrawMode = value;

public new ComboBoxStyle DropDownStyle
        return base.DropDownStyle;
        if (value == ComboBoxStyle.Simple)
            throw new NotSupportedException("ComboBoxStyle.Simple not supported");
        base.DropDownStyle = value;

I overrode OnDataSourceChanged so that the column names could be initialized.

protected override void OnDataSourceChanged(EventArgs e)


private void InitializeColumns()
    PropertyDescriptorCollection propertyDescriptorCollection = 

    columnWidths = new float[propertyDescriptorCollection.Count];
    columnNames = new String[propertyDescriptorCollection.Count];

    for (int colIndex = 0; colIndex < propertyDescriptorCollection.Count; colIndex++)
        String name = propertyDescriptorCollection[colIndex].Name;
        columnNames[colIndex] = name;

I use the DataManager property which returns the CurrencyManager objects that managed the bound objects for the control. Initially I've also set a widths array to 0 (later the required widths will be calculated). I also override the OnValueMemberChanged method so that I could correctly set the value member column internally which I use in the drawing code to make the value column drawn in bold text.

protected override void OnValueMemberChanged(EventArgs e)


private void InitializeValueMemberColumn()
    int colIndex = 0;
    foreach (String columnName in columnNames)
        if (String.Compare(columnName, ValueMember, true, 
            CultureInfo.CurrentUICulture) == 0)
            valueMemberColumnIndex = colIndex;

OnMeasureItem will be called once for every row in the combobox and that's where I do my width calculations.

protected override void OnMeasureItem(MeasureItemEventArgs e)

    if (DesignMode)

    for (int colIndex = 0; colIndex < columnNames.Length; colIndex++)
        string item = Convert.ToString(
            FilterItemOnProperty(Items[e.Index], columnNames[colIndex]));
        SizeF sizeF = e.Graphics.MeasureString(item, Font);
        columnWidths[colIndex] = Math.Max(columnWidths[colIndex], sizeF.Width);

    float totWidth = CalculateTotalWidth();

    e.ItemWidth = (int)totWidth;

The interesting trick here is to use FilterItemOnProperty to get the text associated with a specific column. The width calculation is elementary and I calculate the total width using a CalculateTotalWidth method which merely adds all the individual column widths. I also add width for the vertical scrollbar (in case one shows up). We must also remember to override OnDropDown to set the drop down width appropriately (remember this is different from the width of the combobox itself).

protected override void OnDropDown(EventArgs e)
    this.DropDownWidth = (int)CalculateTotalWidth();

Now we come to the meat of the class -the OnDrawItem override.

protected override void OnDrawItem(DrawItemEventArgs e)

    if (DesignMode)


    Rectangle boundsRect = e.Bounds;
    int lastRight = 0;

    using (Pen linePen = new Pen(SystemColors.GrayText))
        using (SolidBrush brush = new SolidBrush(ForeColor))
            if (columnNames.Length == 0)
                    Font, brush, boundsRect);
                for (int colIndex = 0; colIndex < columnNames.Length; colIndex++)
                    string item = Convert.ToString(FilterItemOnProperty(
                        Items[e.Index], columnNames[colIndex]));

                    boundsRect.X = lastRight;
                    boundsRect.Width = (int)columnWidths[colIndex] + columnPadding;
                    lastRight = boundsRect.Right;

                    if (colIndex == valueMemberColumnIndex)
                        using (Font boldFont = new Font(Font, FontStyle.Bold))
                            e.Graphics.DrawString(item, boldFont, brush, boundsRect);
                        e.Graphics.DrawString(item, Font, brush, boundsRect);

                    if (colIndex < columnNames.Length - 1)
                        e.Graphics.DrawLine(linePen, boundsRect.Right, boundsRect.Top, 
                            boundsRect.Right, boundsRect.Bottom);


Though it's the longest function in the class (and probably exceeds the Marc Clifton approved limit for maximum number of lines in a method), it's quite straightforward. For each row, it iterates through all the columns, gets the column text and draws the text along with vertical lines that will act as column separators.


  • Rama Krishna Vavilala - For some awesome suggestions on the implementation.


  • July 27th 2007 - Article first published.


This article, along with any associated source code and files, is licensed under The BSD License


About the Author

Nish Nishant

United States United States
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.

Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff -

Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.

Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.

Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Comments and Discussions

GeneralRe: Display only columns you want to see Pinmembersgissinger15-Mar-11 7:52 
GeneralRe: Display only columns you want to see PinmemberJosef Meile27-Jun-12 2:56 
GeneralRe: Display only columns you want to see PinmemberJosef Meile27-Jun-12 6:20 
GeneralRe: Display only columns you want to see PinmemberceaTIMETRAK5-Dec-12 5:27 
GeneralRe: Display only columns you want to see Pinmembersgissinger5-Dec-12 7:45 
GeneralGetting the Calculated value for a new column of a DataTable in .NET Pingroupelizas30-Mar-10 4:11 
GeneralRe: Getting the Calculated value for a new column of a DataTable in .NET Pinmemberkevininstructor9-Dec-12 4:23 
Generalaccessing a column value PinmemberMember 13707246-Aug-09 6:57 
Hi Nish,

Thanks for your expertise. I have a questions...

I have bound to a datasource as follows:
var k4 = from p in ctx.vtblCustomerDivisions where == true orderby select new {,, p.vtblCustomers.custId, p.division, p.address, };
cboCustomerDivCd.DataSource = k4;
cboCustomerDivCd.DisplayMember = "custId";
cboCustomerDivCd.ValueMember = "cd";
cboCustomerDivCd.SelectedIndex = -1;
cboCustomerDivCd.Text = "";
cboCustomerDivCd.BackColorOdd = rowColor;
cboCustomerDivCd.ColumnWidths = "0;0;100;100;100;100";

And when the user selects an item I want to set the text in a label to of the 4th column (division) of the selected item in the cobobox list.
Is there a way to get the 4th column of the selected item to do that?

Rich B
QuestionHow do we bind it to SQL Datasource PinmemberMember 197457030-Mar-09 4:56 
GeneralRe: How do we bind it to SQL Datasource (exception error) [modified] PinmemberMember 197457031-Mar-09 1:38 
GeneralRe: How do we bind it to SQL Datasource (exception error) PinsitebuilderNishant Sivakumar1-Apr-09 10:57 
GeneralRe: How do we bind it to SQL Datasource (exception error) PinmemberMember 19745701-Apr-09 16:13 
AnswerRe: How do we bind it to SQL Datasource (exception error) PinmemberMember 197457015-Apr-09 19:33 
QuestionHow do we add this to my VS 2005 project please? PinmemberMember 197457027-Mar-09 5:42 
AnswerRe: How do we add this to my VS 2005 project please? PinsitebuilderNishant Sivakumar27-Mar-09 5:46 
GeneralRe: How do we add this to my VS 2005 project please? PinmemberMember 197457027-Mar-09 6:34 
QuestionCant add this Multicolum to toolbox ? Pinmembersoftkey24-Mar-09 2:35 
AnswerRe: Cant add this Multicolum to toolbox ? PinsitebuilderNishant Sivakumar27-Mar-09 5:47 
GeneralRe: Cant add this Multicolum to toolbox ? PinmemberAsif Rehman4-Jun-11 2:44 
GeneralColumn Headings Pinmemberkevinlkingma2-Dec-08 6:27 
GeneralVertical Scroll PinmemberPaul Gill20-Nov-08 5:33 
GeneralRe: Vertical Scroll PinmemberChris Spicer27-Aug-13 7:05 
GeneralCouple of things PinmemberMicrodev27-Dec-07 2:15 
QuestionAutocomplete Pinmemberksumm31-Oct-07 7:33 
GeneralDrop Down displays 1 character only Pinmemberalias4724-Oct-07 17:33 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150331.1 | Last Updated 27 Jul 2007
Article Copyright 2007 by Nish Nishant
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid