I want to set name and value pairs for combobox. So I created a class named Item
like this:
// Content item for the combo box
private class Item
{
private readonly string Name;
private readonly int Value;
private Item(string _name, int _value)
{
Name = _name; Value = _value;
}
private override string ToString()
{
// Generates the text shown in the combo box
return Name;
}
}
And data set like this:
comboBox1.DataSource = null;
comboBox1.Items.Clear();
// For example get from database continentals.
var gets = _connection.Continentals;
comboBox1.Items.Add(new Item("--- Select a continental. ---", 0));
foreach (var get in gets)
{
comboBox1.Items.Add(new Item(get.name.Length > 40 ? get.name.Substring(0, 37) + "..." : get.name, Convert.ToInt32(get.id)));
}
// It points Africa.
comboBox1.SelectedValue = 3;
Here is the output:
// 1 - Europe
// 2 - Asia
// 3 - Africa
// 4 - North America
// 5 - South America
// 6 - Australia
// 7 - Antartica
In my example The Africa continental must be selected but it is not.
And more than that in my edit form, for example this code gets datas from person
table:
var a = _connection.persons.SingleOrDefault(x => x.id == Id);
When I code comboBox2.SelectedValue = a.continental
, the Africa continental must be selected, but it is not. I did not solve the problem.