I have a form with a lot of user input controls; most of them are optional, and for reasons beyond my control the required elements are scattered around the form. I've been asked to add a button that opens a second form (henceforth called ChildForm) which is linked to the original form (henceforth called ParentForm) and has only the required controls from ParentForm.
I want the controls in ChildForm to be linked to the same datasource as their corresponding controls in ParentForm. I'd like to create this linkage programmatically in a loop so that later changes to ParentForm don't require manually editing the databindings of ChildForm controls.
I tried ChildControl.DataBindings.Add(ParentControl.DataBindings[0]);
but I get a dataBinding belongs to another BindingsCollection
ArgumentException at runtime.
How can I bind a new control to the same column of a DataTable as an existing control without manually doing it for each control?
If your Binding
is simple (doesn't have any Format
and Parse
event handler registered), you can do a shallow clone like this:
public void CloneBinding(Control control, Binding bind){
Binding bind = new Binding(bind.PropertyName, bind.DataSource, bind.BindingMemberInfo.BindingMember);
control.DataBindings.Add(bind);
}
//Use it
CloneBinding(ChildControl, ParentControl.DataBindings[0]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.