Reputation: 1185
I'm trying to use a List<> of objects of my custom class as a source for ListBox. The problem is the instead of strings showing up as an item in my ListBox the whole string is broken down and individual chars are turned into ListBox items. Below are my class and replication to ListBox. I store a list in another class.
What am I doing wrong? Or maybe there is a better way of binding ListBox to List<>?
Listing 1 - replication
BindingSource bds1 = new BindingSource(_newProspectiveCustomer.PhoneNumbers, "PhoneNumber");
phonesListBox.BeginUpdate();
phonesListBox.DataSource = bds1;
phonesListBox.EndUpdate();
Listing 2 - class
public class PCPhone : IEnumerable<string>
{
public string Dma { get; set; }
public IEnumerator<string> GetEnumerator()
{
yield return Dma;
yield return PhoneNumber;
yield return IndexOrder.ToString();
yield return Type.ToString();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
private string _phoneNumber,
_type,
_notes;
private int _indexOrder;
public event EventHandler PhoneChanged;
public string PhoneNumber
{
get
{
return _phoneNumber;
}
set
{
_phoneNumber = value;
CleanPhoneString();
}
}
public string Type
{
get
{
return _type;
}
set
{
_type = value;
}
}
public string Notes
{
get
{
return _notes;
}
set
{
_notes = value;
}
}
public int IndexOrder
{
get
{
return _indexOrder;
}
set
{
_indexOrder = value;
}
}
private void CleanPhoneString()
{
if(_phoneNumber.IndexOf("(") > -1)
_phoneNumber = _phoneNumber.Remove('(');
if(_phoneNumber.IndexOf(")") > -1)
_phoneNumber = _phoneNumber.Remove(')');
if(_phoneNumber.IndexOf(" ") > -1)
_phoneNumber = _phoneNumber.Remove(' ');
if(_phoneNumber.IndexOf("-") > -1)
_phoneNumber = _phoneNumber.Remove('-');
}
public PCPhone(string t, int i, string num)
{
_type = t;
_indexOrder = i;
_phoneNumber = num;
CleanPhoneString();
}
}
Upvotes: 3
Views: 15145
Reputation:
Assuming list is a List of PCPhone just
BindingSource bds1 = new BindingSource() { DataSource = list };
listBox1.DisplayMember = "PhoneNumber";
listBox1.ValueMember = ... ; // value member
listBox1.DataSource = bds1;
or just set directly the list to the listBox1 datasource
listBox1.DisplayMember = "PhoneNumber";
listBox1.ValueMember = ... ; // value member
listBox1.DataSource = list;
Upvotes: 2