I would like to populate a combobox with the following:
Visible item / Item Value
English / En
Italian / It
Spainish / Sp
etc...
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"});
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
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"));
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";
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.
No need to use a particular class Language,
Just replace it with :
KeyValuePair<string,string>