Populating a ComboBox using C#

后端 未结 10 1392
不知归路
不知归路 2020-12-02 15:55

I would like to populate a combobox with the following:

Visible item / Item Value

English / En

Italian / It

Spainish / Sp 

etc...         


        
相关标签:
10条回答
  • 2020-12-02 16:06

    Create a class Language

    public class Language
    {
         public string Name{get;set;}
         public string Value{get;set;}
         public override string ToString() { return this.Name;}
    }
    

    Then, add as many language to the combobox that you want:

    yourCombobox.Items.Add(new Language{Name="English",Value="En"});
    
    0 讨论(0)
  • 2020-12-02 16:09

    but do you not just get your combo box name and then items.add("")?

    For instance

    Language.Items.Add("Italian");
    Language.Items.Add("English");
    Language.Items.Add("Spanish");
    

    Hope this helped :D

    0 讨论(0)
  • 2020-12-02 16:12

    Set the ValueMember/DisplayMember properties to the name of the properties of your Language objects.

    class Language
    {
        string text;
        string value;
    
        public string Text
        {
            get 
            {
                return text;
            }
        }
    
        public string Value
        {
            get
            {
                return value;
            }
        }
    
        public Language(string text, string value)
        {
            this.text = text;
            this.value = value;
        }
    }
    
    ...
    
    combo.DisplayMember= "Text";
    combo.ValueMember = "Value";
    combo.Items.Add(new Language("English", "en"));
    
    0 讨论(0)
  • 2020-12-02 16:19

    Simple way is:

    Dictionary<string, string> dict = new Dictionary<string, string>()
    {
        {"English ","En" },
        {"Italian  ","It" },
        {"Spainish  ","Sp " }
    };
    
    combo.DataSource = new BindingSource(dict, null);
    combo.DisplayMember = "Key";
    combo.ValueMember = "Value";
    
    0 讨论(0)
  • 2020-12-02 16:20

    To make it read-only, the DropDownStyle property to DropDownStyle.DropDownList.

    To populate the ComboBox, you will need to have a object like Language or so containing both for instance:

    public class Language {
        public string Name { get; set; }
        public string Code { get; set; }
    }
    

    Then, you may bind a IList to your ComboBox.DataSource property like so:

    IList<Language> languages = new List<Language>();
    languages.Add(new Language("English", "en"));
    languages.Add(new Language("French", "fr"));
    
    ComboxBox.DataSource = languages;
    ComboBox.DisplayMember = "Name";
    ComboBox.ValueMember = "Code";
    

    This will do exactly what you expect.

    0 讨论(0)
  • 2020-12-02 16:22

    No need to use a particular class Language,

    Just replace it with :

    KeyValuePair<string,string>
    
    0 讨论(0)
提交回复
热议问题