asp.netuser-controlswebformsloadcontrol

Getting data from child controls loaded programmatically


I've created 2 controls to manipulate a data object: 1 for viewing and another for editing.

On one page I load the "view" UserControl and pass data to it this way:

ViewControl control = (ViewControl)LoadControl("ViewControl.ascx");
control.dataToView = dataObject;
this.container.Controls.Add(control);

That's all fine and inside the control I can grab that data and display it.

Now I'm trying to follow a similar approach for editing. I have a different User Control for this (with some textboxes for editing) to which I pass the original data the same way I did for the view:

EditControl control = (EditControl)LoadControl("EditControl.ascx");
control.dataToEdit = dataObject;
this.container.Controls.Add(control);

Which also works fine.

The problem now is getting to this data. When the user clicks a button I need to fetch the data that was edited and do stuff with it. What's happening is that because the controls are being added programmatically, the data that the user changed doesn't seem to be accessible anywhere.

Is there a solution for this? Or is this way of trying to keep things separated and possibly re-usable not possible?

Thanks in advance.


Solution

  • Here's my solution:

    In the page, I keep a reference to the control that is loaded programmatically. In the control I created a GetData() method that returns an object with the data entered by the user. When the user submits the form, the page calls the GetData() method on the control to access the data the user entered.