Click here to Skip to main content
12,953,700 members (40,637 online)
Click here to Skip to main content
Add your own
alternative version

Stats

83.6K views
409 downloads
38 bookmarked
Posted 14 Feb 2006

Unbound items in a bound ComboBox

, 25 Feb 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Itay Sagui
Team Leader
Israel Israel
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#.

You may also be interested in...

Comments and Discussions

 
QuestionProblem wirh wrappers Pin
PeterLevin22-Nov-07 20:38
memberPeterLevin22-Nov-07 20:38 
GeneralAnother way... Pin
JamesTids11-Sep-07 4:13
memberJamesTids11-Sep-07 4:13 
GeneralDoesn't work with anything other than strings Pin
Johnno744-Jul-07 16:26
memberJohnno744-Jul-07 16:26 
Questionuse wrapper with RelatedView Pin
benblo27-Jul-06 4:23
memberbenblo27-Jul-06 4:23 
GeneralNot working with DataView and SelectedValue [modified] Pin
aBrookland6-Jun-06 1:24
memberaBrookland6-Jun-06 1:24 
GeneralSmall Bug Pin
koby_m25-Feb-06 11:17
memberkoby_m25-Feb-06 11:17 
GeneralInsert item to bound drop down list Pin
jbrathwaite23-Feb-06 9:36
memberjbrathwaite23-Feb-06 9:36 
GeneralRe: Insert item to bound drop down list Pin
Itay Sagui23-Feb-06 10:51
memberItay Sagui23-Feb-06 10:51 
GeneralRe: Insert item to bound drop down list Pin
jbrathwaite23-Feb-06 21:19
memberjbrathwaite23-Feb-06 21:19 
GeneralRe: Insert item to bound drop down list Pin
gimpyyyyyyy7-Aug-07 10:55
membergimpyyyyyyy7-Aug-07 10:55 

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 | Terms of Use | Mobile
Web02 | 2.8.170525.1 | Last Updated 25 Feb 2006
Article Copyright 2006 by Itay Sagui
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid