Click here to Skip to main content
15,881,248 members
Articles / Desktop Programming / Windows Forms
Article

Unbound items in a bound ComboBox

Rate me:
Please Sign up or sign in to vote.
4.25/5 (13 votes)
25 Feb 2006CPOL2 min read 97K   462   38   10
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.

C#
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.

C#
#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:

C#
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:

C#
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)


Written By
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#.

Comments and Discussions

 
QuestionProblem wirh wrappers Pin
PeterLevin22-Nov-07 20:38
PeterLevin22-Nov-07 20:38 
GeneralAnother way... Pin
JamesTids11-Sep-07 4:13
JamesTids11-Sep-07 4:13 
If you are using a DataTable as a source to your combo then you could always just add a new row before you attach it.

Example;

<br />
DataTable tblCategory = CategoryDS.Tables["Category"];<br />
               DataRow NewRow = tblCategory.NewRow();<br />
                tblCategory.Rows.InsertAt(NewRow,0);<br />
                NewRow[0] = "-- Click to select --";<br />
<br />
cboCategory.DataSource = tblCategory;<br />
                    cboCategory.DisplayMember = "CategoryID";<br />
                    cboCategory.ValueMember = "Category";<br />
                    cboCategory.SelectedIndex = 0;<br />
<br />

GeneralDoesn't work with anything other than strings Pin
Johnno744-Jul-07 16:26
Johnno744-Jul-07 16:26 
Questionuse wrapper with RelatedView Pin
benblo27-Jul-06 4:23
benblo27-Jul-06 4:23 
GeneralNot working with DataView and SelectedValue [modified] Pin
aBrookland6-Jun-06 1:24
aBrookland6-Jun-06 1:24 
GeneralSmall Bug Pin
kobymeir25-Feb-06 11:17
kobymeir25-Feb-06 11:17 
GeneralInsert item to bound drop down list Pin
jbrathwaite23-Feb-06 9:36
jbrathwaite23-Feb-06 9:36 
GeneralRe: Insert item to bound drop down list Pin
Itay Sagui23-Feb-06 10:51
Itay Sagui23-Feb-06 10:51 
GeneralRe: Insert item to bound drop down list Pin
jbrathwaite23-Feb-06 21:19
jbrathwaite23-Feb-06 21:19 
GeneralRe: Insert item to bound drop down list Pin
gimpyyyyyyy7-Aug-07 10:55
gimpyyyyyyy7-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.