Search code examples
c#winformscombobox

c# - how can I update ComboBox


I have one form with a DataGridView and combobox. Combobox is filled through DataSource in properties menu and I specify DisplayMember and ValueMember through this menu as well. I have a button that when I click on it another form will show and I can add a new item to my combobox's data source. When I close this new form I want my comobox's datasource to refresh that I can see the new item that I just added in combobox, but I don't know how.

I have tried:

myComboBox.Refresh();

but nothing happened

and I also tried this:

myComboBox.Items.Add(myclass.myNewItem);

but it throws an Exception:

items collection cannot be modified when the datasource property is set.

Is anyone can help me, please?

EDIT: I figured out that when I added a new item in second form everything is fine and new item is also add to database, but when I return to first form sounds like nothings happened. So I add listBox to second form and I saw nothing added after coming back to first form.I really don't know why combobox and listbox use old datasource even though my database changed. then I tried this and it worked:

In the second form I saved my new item in a class(named transfer) and when I returned to first form did this:

        DsMy.tblRow row = dsMy.tbl.NewtblRow();
        row.BeginEdit();
        row.Name = transfer.newName;
        row.Id = transfer.newId;
        row.EndEdit();

        dsMy.tbl.AddtblRow(row);


        this.Validate();
        tblTableAdapter.Update(dsMy.tbl);
        myComboBox.Refresh();

thanks everybody for your help! :)


Solution

  • All I had to do was to fill up TableAdapter and then refresh combobox:

        tblTableAdapter.Fill(dsMy.tbl);
        myComboBox.Refresh();