DataBind property of class which derives from CollectionBase

J

Joe

I want to bind to the property Caption but can't. I get the exception:
"Cannot bind to property or column Caption on DataSource.
Parameter name: dataMember"

public class Test : CollectionBase
{
private string caption;

public string Caption
{
get
{
return caption;
}
set
{
caption = value;
}
}
}

Is there anyway to do this when a class derives from CollectionBase?

Thanks,
Joe
 
M

Marc Gravell

How are you setting the datasource? BindingSource, for instance, will
accept a single object *or* an object that implements IList to mean a
set of objects. I suspect you are trying to use the first (single
object) case; since CollectionBase : IBindingSource, it could be
thinking you mean to give it a set of objects, and thus be a level out
(if you see what I mean). Try placing your object into a List<T>, and
set *that* (list) as the datasource.

Marc
 
M

Marc Gravell

Can reproduce on demand; see fix below: (remove marked line and
uncomment remaining 3):

class Test : System.Collections.CollectionBase {
public string Caption { get { return "Working"; } }
}
class Program {
static void Main() {
Test obj = new Test();
using (Form f = new Form())
using(BindingSource bs = new BindingSource()) {
bs.DataSource = typeof(Test);
f.DataBindings.Add("Text", bs, "Caption");
bs.DataSource = obj; // breaks
//List<Test> allData = new List<Test>();
//allData.Add(obj);
//bs.DataSource = allData;
f.ShowDialog();
}
}
}

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top