DataBinding to Properties of a Collection

  • Thread starter Thread starter charlie
  • Start date Start date
C

charlie

I have been messing around with data binding on Windows Forms, and I'm
having a problem with the Property of a Collection (myCollection.Count)
getting out of synch with label it's bound to.

(My real problem is binding to a Property of a Collection, and not just
the simpler case of the .Count property)

I'm using the following syntax to bind the object to the label.

1.) label1.DataBindings.Add("Text", myCollection.Count, "");

If I then add a new item to my collection through code, the label for
the Count does not get updated. I initially had this problem with a
simple object that has a TotalPrice property that is a calculated field
(based on Quantity * UnitPrice) , but I was able to add an event that
triggered the GUI to get the new calculated value.

public event EventHandler TotalPriceChanged;

public void OnTotalPriceChanged()
{
if (TotalPriceChanged!= null)
TotalPriceChanged(this, new EventArgs());
}

public int TotalPrice
{
get
{
return _totalPrice;
}
set
{
_totalPrice = value;
OnTotalPriceChanged();
}
}

In this case I had to use the following syntax to bind the TotalPrice,
where I specify the 3rd parameter as the property name, instead of
including it in the 2nd parameter as I did above.

2.) label1.DataBindings.Add("Text", myObj, "TotalPrice");

However, if I'm binding to a Property of a Collection using the Syntax
from #2, I get an System.ArgumentException 'Can not bind to property or
column Count on datasource.' What I think is going on here is that it's
trying to bind to the Currently Selected Item in the Collection, which
does not have a Count property.

Am I just missing something, or do Properties of Collections not have
any way to bind and keep their data synchronized between the Collection
object and the GUI?

TIA,
Charlie
 
Charlie,

You are correct, when you do this:

label1.DataBindings.Add("Text", myCollection, "Count");

the binding code is trying to find Count property on element of the
collection.

What you could do is create a simple wrapper class for your collection with
Count property and CountChanged event and bound to it.

Alexander
 
Charlie,

You are correct, when you do this:

label1.DataBindings.Add("Text", myCollection, "Count");

the binding code is trying to find Count property on element of the
collection.

What you could do is create a simple wrapper class for your collection with
Count property and CountChanged event and bind to it.

Alexander
 
Back
Top