How to solve this ComboBox item setting problem?
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开发者_JS百科 void button1_Click(object sender, EventArgs e)
{
int ID = 5;//This is what I have.
comboBox1.SelectedItem = .............how?
}
}
I believe your Equals comparison may be incorrect. For NHibernate, I use the following Equals()
method:
public static class EntityUtil
{
public static bool Equals(IEntity a, IEntity b)
{
// Transient entitys are never equal (unless they are ReferenceEquals)!
return
ReferenceEquals(a, b) || (
!((object)a == null || (object)b == null) &&
!(IsTransient(a) || IsTransient(b)) &&
NHibernateProxyHelper.GetClassWithoutInitializingProxy(a) == NHibernateProxyHelper.GetClassWithoutInitializingProxy(b) &&
a.Id.Equals(b.Id)
);
}
public static bool IsTransient(IEntity entity)
{
return entity.Id == 0;
}
}
I have defined this method in a separate helper class and use this in my entity:
public class Entity : IEquatable<Entity>, IEquatable<IEntity>
{
private int? _hashCode;
public virtual int Id { get; protected set; }
public override bool Equals(object obj)
{
return EntityUtil.Equals((IEntity)this, obj as IEntity);
}
public virtual bool Equals(Entity obj)
{
return EntityUtil.Equals((IEntity)this, (IEntity)obj);
}
public virtual bool Equals(IEntity obj)
{
return EntityUtil.Equals((IEntity)this, obj);
}
public static bool operator ==(Entity a, Entity b)
{
return EntityUtil.Equals((IEntity)a, (IEntity)b);
}
public static bool operator !=(Entity a, Entity b)
{
return !(a == b);
}
public override int GetHashCode()
{
// GetHashCode needs to return a stable value.
if (!_hashCode.HasValue)
{
_hashCode =
NHibernateProxyHelper.GetClassWithoutInitializingProxy(this).GetHashCode() ^
((IEntity)this).Id.GetHashCode();
}
return _hashCode.Value;
}
}
This is the suggested implementation for working with equality with NHibernate. Maybe this helps for you too.
精彩评论