This code is not setting right value to the combobox. This is because, those are from different contexts.
In addition, in my actual problem, neither overloading == in nor overriding Equals() in MyClass is working as well.
Any alternative way?
How to solve this problem?
MyClass.cs
public class MyClass
{
public int ID { get; set; }
public string Name { get; set; }
public MyClass(int id, string name)
{
ID = id;
Name = name;
}
public static List<MyClass> Get()
{
return new List<MyClass>
{
new MyClass(2, "AAA"),
new MyClass(4, "BBB"),
new MyClass(5, "CCC"),
new MyClass(7, "DDD"),
new MyClass(10, "EEE")
};
}
}
ComboBoxForm.cs
public partial class ComboBoxForm : Form
{
public ComboBoxForm()
{
InitializeComponent();
}
private void Form1_Shown(object sender, EventArgs e)
{
LoadDataToComboBoxFromDatabase();
}
private void LoadDataToComboBoxFromDatabase()
{
comboBox1.Items.Clear();
List<MyClass> list = MyClass.Get();
foreach(MyClass mc in list)
{
comboBox1.Items.Add(mc);
}
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
comboBox1.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
int ID = 5;//This is what I have.
comboBox1.SelectedItem = .............how?
}
}