Post

How to data bind a ToolStripComboBox

Normally, the ToolStripComboBox doesn’t have any properties for data binding. But you can still data bind this combobox with the method I describe here. Since the ToolStripComboBox hosts a Control that inherits from ComboBox, you can type cast to a ComboBox and do the data binding.

In this example I will bind the ToolStripComboBox to an ArrayList which consists of objects of the type ColorTypes.

So, lets get started. First create the ColorType class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
namespace WindowsFormsApplication1
{
    public class ColorType
    {
        private int _ID;
        public int ID
        {
            get { return _ID; }
            set {_ID = value; }
        }

        private string _Name;
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        public ColorType(int id, string name)
        {
            _ID = id;
            _Name = name;
        }
    }
}

Second, in the Form that hosts the TollStripComboBox, create an ArrayList of the objects. In the Load method, cast the ToolStripComboBox to a ComboBox and do the data binding.

And finally, in the SelectedIndexChanged event for the ToolStripComboBox, type cast to a ComboBox and read out the SelectedValue property.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private ArrayList arrListColorTypes;
        public Form1()
        {
            InitializeComponent();

            arrListColorTypes = new ArrayList();
            arrListColorTypes.Add(new ColorType(0, "Red"));
            arrListColorTypes.Add(new ColorType(1, "Green"));
            arrListColorTypes.Add(new ColorType(2, "Blue"));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ComboBox cb = ((ComboBox)toolStripComboBox1.Control);
            cb.DisplayMember = "Name";
            cb.ValueMember = "ID";
            cb.DataSource = arrListColorTypes;
        }

        private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = Convert.ToInt32(((ComboBox)toolStripComboBox1.Control).SelectedValue);
            switch (index)
            {
                case 0: // Do the Red dance
                    break;
                case 1: // Do the Green dance
                    break;
                case 2: // Do the Blue dance
                    break;
            }
        }
    }
}

This post is licensed under CC BY 4.0 by the author.