Hi,

I have a combobox which gets data from a dataset called cmbItemType, now i would like to let the user add another item type in the combo boc withot haveing to create another form.

can u help me pls?

private void comboBox1_KeyDown(object sender, KeyEventArgs e) {
    if (e.KeyCode == Keys.Enter) {
        comboBox1.Items.Add(comboBox1.Text);
        e.Handled = true;
    }
}

You'll probably have issues with the dataset as databound controls don't like to be changed.

Edited 5 Years Ago by Momerath: n/a

Yep, this will not do, it the comboBox is bound to a dataSet.
Try this one:

private void comboBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int newID = Convert.ToInt32(table.Rows[table.Rows.Count - 1]["Id"]);
                newID++;//add new id - add 1 to last id
                //insert a new row to dataTable:
                DataRow dr;
                dr = table.NewRow();
                dr["Id"] = newID++;  
                dr["Name"] = comboBox1.Text;
                table.Rows.Add(dr);
            }
            else if (e.KeyCode == Keys.Escape)
                this.Focus();
        }

Consider that dataTable is done this way:

table = new DataTable("MyTable");
            DataColumn[] columns = new DataColumn[] { 
               new DataColumn("Id", typeof(int)), 
               new DataColumn("Name", typeof(string)) };
            table.Columns.AddRange(columns);

Ok thx i will try them both :-) sry i couldnt get to you yesterday as i was too busy i will let you know if it worked.. THANKS again!

This article has been dead for over six months. Start a new discussion instead.