I have a combo box. I want to make it editable on click of an item so that user can add new item to the combo box.

Please find the code below.

private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1 = new ComboBox();
            comboBox1.Location = new Point(20, 60);
            comboBox1.Name = "comboBox1";
            comboBox1.Size = new Size(245, 25);

            comboBox1.Items.Add("A");
            comboBox1.Items.Add("B");
            comboBox1.Items.Add("C");
            comboBox1.Items.Add("D");
            comboBox1.Items.Add("Add");

            this.Controls.Add(comboBox1);
            comboBox1.DrawItem += comboBox1_DrawItem;
            comboBox1.SelectedValueChanged += OnComboBox1SelectionChanged;
        }

        private void OnComboBox1SelectionChanged(object sender, EventArgs e)
        {
            if (((ComboBox)sender).SelectedItem.ToString() == "Add")
            {
                //
            }
        }

        private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();
            if (e.Index > -1)
            {
                e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds);
            }
        }

    private void Save_Click(object sender, EventArgs e)
        {

        }

Here, if the user clicks "Add", i want to make the combobox editable which will actualy let the user type a new data in the combo box and
on clicking "Save", add the item to the combo box and make it readable. user should be able to Add as many items as they wish to.

Can we do that. I googled but could'nt find.
Please let me know how we can do that.

Hmm, seems awkward. I'd probably start by trying something like this:

private bool _addingItem = false;

private void comboBox_SelectionChangeCommitted(object sender, EventArgs e)
{
    var ctrl = sender as ComboBox;

    if (ctrl.SelectedItem.ToString() == "Add")
    {
        _addingItem = true;
        ctrl.Focus();
    }
}

private void comboBox_KeyDown(object sender, KeyEventArgs e)
{
    if (!_addingItem)
    {
        return;
    }

    var ctrl = sender as ComboBox;

    if (e.KeyCode == Keys.Enter)
    {
        if (!ctrl.Items.Contains(ctrl.Text))
        {
            ctrl.Items.Add(ctrl.Text);
            ctrl.Invalidate();
            e.Handled = true;
        }
    }
}

private void comboBox_Leave(object sender, EventArgs e)
{
    _addingItem = false;
}

Obviously there are plenty of use cases to consider, but for the basic functionality the above seems like a reasonable start.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.