How to add an item to a ComboBox at run time

Marc Graham 26 Reputation points
2024-04-01T20:57:57.0766667+00:00

The combobox is in a DataGridView. for what it's worth.This used to be doable, but since I went to w11 -- and downloaded a new compiler -- it seems to no longer be possible. That's very annoying.

Anything I can do?

Developer technologies | .NET | Other
Developer technologies | C#
{count} votes

2 answers

Sort by: Most helpful
  1. hossein jalilian 11,055 Reputation points Volunteer Moderator
    2024-04-01T21:33:49.2+00:00

    Thanks for posting your question in the Microsoft Q&A forum.

    You can directly add items to the ComboBox's Items collection at runtime using the Items.Add() method. For example, if you have a ComboBox named comboBox1 in a DataGridView, you can add a new item like this:

    comboBox1.Items.Add("New Item");
    

    Another approach is to bind the ComboBox to a data source, such as a DataTable or List<T>, and then add new items to the data source. For example, you can create a DataTable and bind it to the ComboBox, then add a new row to the DataTable:

    DataTable dt = new DataTable();
    dt.Columns.Add("Value");
    dt.Rows.Add("New Item");
    comboBox1.DataSource = dt;
    comboBox1.DisplayMember = "Value";
    comboBox1.ValueMember = "Value";
    
    

    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful

    0 comments No comments

  2. Michael Taylor 60,326 Reputation points
    2024-04-01T21:55:03.79+00:00

    You can add items to combo boxes at runtime. The version of the compiler doesn't matter but the version of the framework you're targeting does. Please provide us the code you're using, the error you're getting, the version of the framework you're targeting, how you're binding your initial data, how you're adding new items and any related information.

    For example if you are data binding to the control (using DataSource) then you cannot add items to it (nor really ever could/should). But unless you updated the framework version then you wouldn't notice this. If you need to dynamically add items to something that is using a data source then you need to either add the items to the data source (because that is the source of the data) or you need to remove the data source and set the Items property directly. This is really how it has always worked AFAIK. Posting the code would help clarify what you're doing.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.