问题
We are running a .NET 4.0 application using Windows Forms. The application uses a single form for two different types of objects.
namespace NetIssue
{
public partial class Form1 : Form
{
B myObj;
public Form1()
{
InitializeComponent();
myObj = new B();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.DataBindings.Add(new Binding("Text", myObj, "c.Message"));
}
}
public class Comment {
public int ID { get; set; }
public string Message { get; set; }
public Comment(string msg)
{
Message = msg;
}
}
public class A {
string MyName = "";
}
public class B : A {
public Comment c { get; set; }
public B()
{
c = new Comment("test");
}
}
}
When the binding above is run in .NET 4.0, we get the error
An error occured: Cannot bind to the property or column Message on the DataSource. Parameter name: dataMember
However, if we install .NET 4.5 this error goes away.
Is this a limitation of .NET 4.0, a bug in .NET 4.0, or is something else going on?
回答1:
Short story: Windows Forms data binding doesn't support property path, that's why you are getting the error.
Well, this is what I was thinking until today. But trying your code I was surprised that it indeed works on .NET 4.5 machine! So looks like MS has added that at some point - to be honest, have no idea when. But it's there now! Anyway, if backward compatibility is a concern, one should avoid using that feature (although it would be quite pity).
回答2:
You can use either of these options:
B myObj = new B();
textBox1.DataBindings.Add(new Binding("Text", ((B)myObj).c, "Message"));
Or
var bs = new BindingSource(myObj, null);
textBox1.DataBindings.Add("Text", bs, "c.Message");
Or
textBox1.DataBindings.Add("Text", new B[] { myObj }, "c.Message");
来源:https://stackoverflow.com/questions/33789575/databinding-to-nested-property-cannot-bind-property-or-column-winforms