First of all thank you Adam Robinson, I'm sure your answer was correct, but it just wasn't what I wanted to hear. I solved my problem in a different way and I think it may be useful to someone else, so I am posting it here.
What I did was I created a new class, in my case I named it ListObject, which had a property DataRow (as you will see later it works for other types too, I just used this since this is what I actually wanted as my Item value property). It also overrides methods:
- String ToString()
- bool Equals(object obj)
- int GetHashCode() --is not needed in my case, however Visual Studio
warns you it should be overridden.
The idea was that I could fill ComboBox.Items collections with objects of my own class, display a custom string (if I had not worked it out like this, my next question on Stack overflow would probably be about customizing DisplayMembers when reading items from a DataRow) and compare only one class's item (in my case DataRow).
So here is the code and it works great (at least for what I wanted to do with it).
public class ListObject
{
public DataRow element;
public String DisplayObject = null;
public ListObject(DataRow dr)
{
element = dr;
}
public ListObject(DataRow dr, String dspObject)
{
element = dr;
DisplayObject = dspObject;
}
public override String ToString()
{
if (DisplayObject == null) throw new Exception("DisplayObject property was not set.");
return element[DisplayObject].ToString();
}
public override bool Equals(object obj)
{
if (obj.GetType() == typeof(ListObject))
return Equals(((ListObject)obj).element, this.element);
else return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
In my case it works great since I can just fill the ComboBox's with a foreach statement:
dtUsers.ReadXml(Program.Settings.xmlInputUsers);
foreach(DataRow dr in dtUsers.Rows)
{
cmbUser.Items.Add(new ListObject(dr, "Name"));
}
And when I get the DataRow I want selected I just do this:
cmbUser.SelectedItem = new ListObject(dlg.SelectedDataRow);
Where I don't have to worry about the DisplayMember etc, because only DataRow's will be compared, and your display parameters will still be set from when you filled ComboBox.Items collection. Also since toString method is overridden you can really customize your output.
Creating this class was only possible because of msdn article on ComboBox.SelectedItem Property in which it was noted, that SelectedItem property works using the IndexOf method. This method uses the Equals method to determine equality.