Click here to Skip to main content
Licence CPOL
First Posted 14 Feb 2006
Views 70,376
Bookmarked 37 times

Unbound items in a bound ComboBox

By | 25 Feb 2006 | Article
This article shows how to add unbound items to a bound ComboBox.

Introduction

It is sometimes necessary to add items to a bound ComboBox that will appear at the beginning of the drop-down list. If you ever tried to add items to a ComboBox that was bound, you probably know that an ArgumentException is thrown, saying that "Cannot modify the Items collection when the DataSource property is set". Unfortunately for UI programmers, it is required to add items, such as "Create new item…" at the beginning of the list.

The DataSource

In order to permit such functionality, we are going to have to wrap our original DataSource with a class that allows us to add those extra items. The first thing you have to notice is that DataSource, as accepted by the ComboBox, must implement the IList interface. Also, in order to display all the items, we'll have to implement the IEnumerable interface.

public class UnboundWrapper : IEnumerable, IList
{
    public UnboundWrapper(IList dataSource)
    {
        _dataSource = dataSource;
        _extra = new ArrayList();
    }

    IList _dataSource; 
    ArrayList _extra;

    #region ExtraData
    public void AddExtraData(object extraItem)
    {
        _extra.Add(extraItem);
    }

    public void RemoveExtraData(object extraItem)
    {
        _extra.Remove(extraItem);
    }
    #endregion
}

The above code is just our basic skeleton, and shouldn't raise any question. Next, we'll implement the IList and IEnumerable methods. The main idea here is that we're supposed to handle an extra item, and we'll take it from the _extra ArrayList. Otherwise, we just pass the calls along to the contained IList, with a shift of the indices, that is the size of the extra items.

    #region IList Members

    public bool IsReadOnly
    {
        get
        {
            return _dataSource.IsReadOnly;
        }
    }

    public object this[int index]
    {
        get
        {
            string val;
            if (index < _extra.Count)
                val = _extra[index].ToString();
            else
                val = _dataSource[index - 
                      _extra.Count].ToString();
            return val;
        }
        set
        {
            _dataSource[index - _extra.Count] = value;
        }
    }

    public void RemoveAt(int index)
    {
        if (index < _extra.Count)
            throw new InvalidOperationException();
        _dataSource.RemoveAt(index - _extra.Count);
    }

    public void Insert(int index, object value)
    {
        if (index < _extra.Count)
            throw new InvalidOperationException();
        _dataSource.Insert(index - _extra.Count, value);
    }

    public void Remove(object value)
    {
        _dataSource.Remove(value);
    }

    public bool Contains(object value)
    {
        return _dataSource.Contains(value);;
    }

    public void Clear()
    {
        _dataSource.Clear();
    }

    public int IndexOf(object value)
    {
        if (_extra.Contains(value))
            return _extra.IndexOf(value);
        return _dataSource.IndexOf(value) + _extra.Count;
    }

    public int Add(object value)
    {
        return _dataSource.Add(value);
    }

    public bool IsFixedSize
    {
        get
        {
            return _dataSource.IsFixedSize;
        }
    }

    #endregion

    #region ICollection Members

    public bool IsSynchronized
    {
        get
        {
            return _dataSource.IsSynchronized;
        }
    }

    public int Count
    {
        get
        {
            return _dataSource.Count + _extra.Count;
        }
    }

    public void CopyTo(Array array, int index)
    {
        _extra.CopyTo(array, index);
        _dataSource.CopyTo(array, index + _extra.Count);
    }

    public object SyncRoot
    {
        get
        {
            return _dataSource.SyncRoot;
        }
    }

    #endregion

    #region IEnumerable Members

    public IEnumerator GetEnumerator()
    {
        return new UnboundWrapperEnumerator(this);
    }

    #endregion

You'll notice that we've also implemented the ICollection interface. This is because IList inherits from it, leaving us with no choice.

Since we've implemented the IEnumerable interface, we must supply the user with an enumerator. However, we cannot supply the IList's default enumerator, since it won't include the extra items. So now, we have to create a new class - an enumerator:

class UnboundWrapperEnumerator : IEnumerator
{
    public UnboundWrapperEnumerator(UnboundWrapper wrapper)
    {
        _wrapper = wrapper;
    }

    private UnboundWrapper _wrapper;
    int _index = -1;
        
    public void Reset()
    {
        _index = -1;
    }

    public object Current
    {
        get
        {
            return _wrapper[_index];
        }
    }

    public bool MoveNext()
    {
        if (_index >= _wrapper.Count - 1)
            return false;

        _index++;
        return true;
    }
}

As you can see, the enumerator is even simpler that the wrapper itself.

Example

Before we leave, let's have a look at a simple example. Create a new Form, and add a ComboBox to it. In the constructor of the form, add the following code:

string[] items = new string[] {"s1", "s2", "s3"};

UnboundWrapper w1 = new UnboundWrapper(items);
w1.AddExtraData("a");
w1.AddExtraData("b");
w1.AddExtraData("c");
w1.AddExtraData("z");

comboBox1.DataSource = w1;

In the above example, the DataSource is a simple string array. It shouldn't be too hard to expand the code to support more "interesting" data sources, such as a DataSet.

License

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

About the Author

Itay Sagui

Team Leader

Israel Israel

Member

I currently work as the development manager in a company called Tzunami Inc. that develops a content migration solution for Microsoft SharePoint . Our product, called Tzunami Deployer is developed using C#.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionProblem wirh wrappers PinmemberPeterLevin20:38 22 Nov '07  
GeneralAnother way... PinmemberJamesTids4:13 11 Sep '07  
GeneralDoesn't work with anything other than strings PinmemberJohnno7416:26 4 Jul '07  
Hi,
 
Tried this on my project, thought it would be very handy. First problem I hit was the indexer on IWrapper always returns a string - val = _extra[index].ToString();
 
This broke the SelectedItem etc.
 
I removed the ToStrings and changed val to an object
 
The code runs works now, but unfortunately databinding doesn't work properly when you have any extra items Frown | :( My listbox text just contains the name of the class, not the DataMember I specified.
 
I'd guess that under the hood the databinding is caching the pointer to property specified in DisplayMember - and resolving the property to display fails on the first attempt when we have an extra member.
 
I can't think of a way around this problem... Any ideas?
 
Cheers
John

Questionuse wrapper with RelatedView Pinmemberbenblo4:23 27 Jul '06  
GeneralNot working with DataView and SelectedValue [modified] PinmemberaBrookland1:24 6 Jun '06  
GeneralSmall Bug Pinmemberkoby_m11:17 25 Feb '06  
GeneralInsert item to bound drop down list Pinmemberjbrathwaite9:36 23 Feb '06  
GeneralRe: Insert item to bound drop down list PinmemberItay Sagui10:51 23 Feb '06  
GeneralRe: Insert item to bound drop down list Pinmemberjbrathwaite21:19 23 Feb '06  
GeneralRe: Insert item to bound drop down list Pinmembergimpyyyyyyy10:55 7 Aug '07  

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.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120529.1 | Last Updated 25 Feb 2006
Article Copyright 2006 by Itay Sagui
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid