Land Rovers, .Net en meer!
.Net 4.0 WinForm Data Binding bug
Currently I’m busy with converting a .Net 2.0 WinForms application to .Net 4.0 in VS2010. Seemed to work pretty smooth but when testing one of the more complex windows in the application I hit a snag. Upon opening the window I got a “TargetException: Object does not match target type.” thrown in my face. After a quick tour with the debugger I found the problem: data binding didn’t work anymore!
To find out what the real problem was I’ve built a test application that basically does the same thing as the complex window that is giving me such a headache. So here goes:
I have a class like this:
public class Base {
public string Property1 { get; set; }
public Sub SubItem { get; set; }
public Base() {
Property1 = "Base Property1";
SubItem = new Sub();
}
public class Sub {
public string Property1 { get; set; }
public Sub() {
Property1 = "Sub Property1";
}
}
Which is bound to a TextBox:
private void buttonBind_Click(object sender, EventArgs e) {
Base b = new Base();
// This works
textBox1.DataBindings.Add("Text", b.SubItem, "Property1");
// This doesn't work
textBox2.DataBindings.Add("Text", b, "SubItem.Property1");
}
Now the first binding will work but the second one will throw a TargetException. I have no clue why this happens but the message of the exception and the stack trace give some hints that this is a reflection problem. However the binding specifies to bind a string property to a string property so that shouldn’t be a problem.
A workaround for this problem is to use a BindingSource:
private void buttonBind_Click(object sender, EventArgs e) {
Base b = new Base();
BindingSource bs = new BindingSource(b, null); // Use a empty datamember
// Now it will work
textBox2.DataBindings.Add("Text", bs, "SubItem.Property1");
}
But it’s quite a lot of work to replace this in the current application so I hope this gets fixed soon.
In the meanwhile I’ve filed a bug report at Microsoft Connect (see here) with sample code that demonstrates the behavior so you can test for yourself. If you do, please vote on Microsoft Connect to get it under their attention!
| Print artikel | Dit bericht is gepost door Sander op April 21, 2010 om 10:37 am uur en is gearchiveerd onder .Net, C# 4.0. Volg reacties op dit bericht via RSS 2.0. Reacties zijn momenteel uitgeschakeld, maar je kunt trackback van je eigen site. |
Commentaar is gesloten.