none
How add a item to combobox

    Question

  • how i can add a item to combox with value an display value without use a datatable

    Thanks

    Thursday, November 16, 2006 11:41 PM

Answers

  • A ComboBox stores objects, not just strings.  You can store your own object; override the ToString() method to generate the text the user will see.  Here's an example:

      public partial class Form1 : Form {
        // Content item for the combo box
        private class Item {
          public string Name;
          public int Value;
          public Item(string name, int value) {
            Name = name; Value = value;
          }
          public override string ToString() {
            // Generates the text shown in the combo box
            return Name;
          }
        }
        public Form1() {
          InitializeComponent();
          // Put some stuff in the combo box
          comboBox1.Items.Add(new Item("Blue", 1));
          comboBox1.Items.Add(new Item("Red", 2));
          comboBox1.Items.Add(new Item("Nobugz", 666));
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
          // Display the Value property
          Item itm = (Item)comboBox1.SelectedItem;
          Console.WriteLine("{0}, {1}", itm.Name, itm.Value);
        }
      }

    Friday, November 17, 2006 1:56 PM

All replies

  • comboBox.Items.Add("someText")?
    Friday, November 17, 2006 12:07 AM
  • You can write a class with the properties, and put your data into an array. Then also bind it to the combobox, setting the DataMember. This is not what you mean by 'datatable', is it? :-)
    Friday, November 17, 2006 7:02 AM
  • However if you are just trying to add/delete to a combobox which is already bound, you will have to use the add/delete from the datasource/dataset methods. You'll get a runtime error when the combo box is alreay bound and you try to add/delete using the combo box method.
    Friday, November 17, 2006 7:54 AM
  • you can use the following code

    ArrayList s = new ArrayList();

    s.Add("aaa");  s.Add("bbb");  s.Add("ccc"); ...

    this.comboBox2.DataSource = s;

    (or)

    string[] s = {"a","b","c","d","1","2","3","4"};

    this.comboBox2.DataSource = s;

    (or)

    char[] s = {'a','b','c'};

    this.comboBox2.DataSource = s;

    (or)

    this.comboBox2.Items.Add("Select");

    • Proposed as answer by shivajani Monday, December 13, 2010 11:41 AM
    Friday, November 17, 2006 8:47 AM
  • ok ...

    I know that but i need

    Combobox show  |  Select value
    Blue                              1

    Red                                 2

     

    Sample de Listbox of the Visual Web Developer you can add items with (Value to show,value to select) 

    Friday, November 17, 2006 11:35 AM
  • A ComboBox stores objects, not just strings.  You can store your own object; override the ToString() method to generate the text the user will see.  Here's an example:

      public partial class Form1 : Form {
        // Content item for the combo box
        private class Item {
          public string Name;
          public int Value;
          public Item(string name, int value) {
            Name = name; Value = value;
          }
          public override string ToString() {
            // Generates the text shown in the combo box
            return Name;
          }
        }
        public Form1() {
          InitializeComponent();
          // Put some stuff in the combo box
          comboBox1.Items.Add(new Item("Blue", 1));
          comboBox1.Items.Add(new Item("Red", 2));
          comboBox1.Items.Add(new Item("Nobugz", 666));
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
          // Display the Value property
          Item itm = (Item)comboBox1.SelectedItem;
          Console.WriteLine("{0}, {1}", itm.Name, itm.Value);
        }
      }

    Friday, November 17, 2006 1:56 PM
  • Thanks, very helpful!!
    Friday, December 10, 2010 10:01 PM
  • After all these years ? :)wow
    Friday, December 10, 2010 10:04 PM
  • What does it mean comboBox1.Items.Add(new Item("Blue", 1)); ? I know that Items.Add can add a new item to the list but (new Item("Blue",1)) I didn't understand it. Please help me cuz I'm in need   !! I want to add a new item but I wanna change the value instead BLUE I wanna to have 1..


    Everything is possible, nothing is impossible. Just try and you will find that.
    Friday, September 02, 2011 6:34 PM
  • In Visual Basic plzz    !!
    Everything is possible, nothing is impossible. Just try and you will find that.
    Friday, September 02, 2011 6:36 PM
  • That's a part of my code ::

    MaConnexion.Open()
    Dim MaCommande As New SqlCommand
    Dim MonDataReader As SqlDataReader
    MaCommande = MaConnexion.CreateCommand
    MaCommande.CommandType = CommandType.StoredProcedure
    MaCommande.CommandText = "SP_ListeGroupeParCentre"
    MaCommande.Parameters.Add("@IdC", SqlDbType.Int).Value = IdCentre   ' Don't worry I have this integer !!
    MonDataReader = MaCommande.ExecuteReader
    Do While MonDataReader.Read
       Cmb_NomG.Items.Add(New Item(MonDataReader("NomGroupe"), MonDataReader("IdGroupe")))
       'Cmb_NomG.Items.Add(MonDataReader("IdGroupe"))
       'Cmb_NomG.Items.Add(MonDataReader("NomGroupe"))
    Loop
    MonDataReader.Close()


    Public Class Item
        Public Name As String
        Public Value As Integer
        Public Sub New(N As String, V As Integer)
            Name = N
            Value = V
        End Sub
        Public Overrides Function ToString() As String
            Return Value
        End Function
    End Class


    Everything is possible, nothing is impossible. Just try and you will find that.

    • Edited by Saâd HAFFAR Friday, September 02, 2011 7:14 PM I made a mistake
    Friday, September 02, 2011 7:13 PM
  • I don't catch the event SelectedIndexChanged now !! Why plz ?
    Everything is possible, nothing is impossible. Just try and you will find that.
    Friday, September 02, 2011 7:23 PM
  • I have to define  MonDataReader("IdGroupe")  as the returned value of my ComboBox  !! If the user select MonDataReader("NomGroupe") I have to have the value which is contained in MonDataReader("IdGroupe")    !! I need Heeeeeeeeeeelp   !!
    Everything is possible, nothing is impossible. Just try and you will find that.
    Friday, September 02, 2011 7:43 PM
  • well, I tried the same but it throws an error:  Object reference not set to an instance of an object.

    here is the code snippet:

     

                ComboBox cbbx = new ComboBox();
    
                cbbx = comboBox1;
    
                for (int i = 0; i < datatable_Users.Rows.Count; i++)
    
                {
    
                    //comboBox1.Items.Add(datatable_Users.Rows[i]["userName"]);
    
                    //cbbx.Items.Add(datatable_Users.Rows[i]["userName"]);
    
                    comboBox1.Items.Add("test_item"); // <<<<<< here it shows the error !
    
                }
    
            }
    


    Tuesday, January 10, 2012 3:58 AM
  • I just found a way to do it without explicitly defining a new ComboBoxItem Type.

    Ethan

    DataTable comboBoxItems = new DataTable();

    comboBoxItems.Columns.Add("Display");

    comboBoxItems.Columns.Add("Value");

     foreach (GeneCategory category in allCategories)

    {

    DataRow itemRow = comboBoxItems.NewRow();

    itemRow["Display"] = category.CategoryName;

    itemRow["Value"] = category.CategoryId;

    comboBoxItems.Rows.Add(itemRow);

    }

    parentOfBox.DisplayMember = "Display";

    parentOfBox.ValueMember = "Value";

    parentOfBox.DataSource = comboBoxItems;


    Ethan Strauss

    • Proposed as answer by JesusFreak71 Friday, December 21, 2012 8:33 PM
    Friday, June 08, 2012 5:33 PM
  • I really like this solution

    DataTable comboBoxItems = new DataTable();

    comboBoxItems.Columns.Add("Display");

    comboBoxItems.Columns.Add("Value");

     foreach (GeneCategory category in allCategories)

    {

    DataRow itemRow = comboBoxItems.NewRow();

    itemRow["Display"] = category.CategoryName;

    itemRow["Value"] = category.CategoryId;

    comboBoxItems.Rows.Add(itemRow);

    }

    parentOfBox.DisplayMember = "Display";

    parentOfBox.ValueMember = "Value";

    parentOfBox.DataSource = comboBoxItems;

    However, get an error on each of the last 3 lines.

    System.Windows.Controls.ComboBox' does not contain a definition for 'DisplayMember' and no extension method 'DisplayMember' accepting a first argument of type 'System.Windows.Controls.ComboBox' could be found.

    Then the same for 'ValueMember' and 'DataSource'.  I think it has to do with my References but if I include "using System.Windows.Forms;" then my calls to MessageBox are suddenly "ambiguous".

    Does anyone have a suggestion?



    Tuesday, June 04, 2013 7:05 PM
  • DisplayMember, ValueMember and DataSource are properties of System.Windows.Forms.Combobox.  The error message suggests that you are coding a WPF application and not a Windows Forms application.  The WPF ComboBox (System.Windows.Controls.ComboBox) does not have those properties.
    Tuesday, June 04, 2013 7:17 PM
  • Exactly!

    I started this a while ago, walked away and when I returned, had completely forgotten where I started.  Thanks.

    Tuesday, June 04, 2013 7:23 PM
  • you can create a class

    public class test1

    {

    public String  _text;

    public String _Value; 

    public test1(String text,String value)

    {

    _text = text;

    _value=value;

    }

    public String gettext

    {

    set{_text=value;}

    get{return value;}

    }

    }

    public class mainclass

    {

    public void main()

    {

    ......

    comboBox.itmes.add(new test1("name","value"))

    .......

    }

    }

    Tuesday, January 28, 2014 8:50 AM