Retrieving data from child controls programmatically

I created 2 controls to control the data object: 1 for viewing and another for editing.

On one page, I load the โ€œviewโ€ UserControland pass it the data as follows:

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

So that all this is good and inside the control, I can capture this data and display it.

Now I am trying to follow a similar approach for editing. I have another User Control for this (with some text fields for editing), to which I pass the source data in the same way as for the presentation:

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

Which also works great.

Now the problem is with this data. When the user clicks the button, I need to get the data that has been edited, and do everything with it. What happens is that since the controls are added programmatically, the data that the user has changed is not accessible anywhere.

Is there a solution for this? Or is this way of trying to keep things separate and possibly reusable impossible?

Thanks in advance.

0
source share
3 answers

Here is my solution:

, . GetData(), , . , GetData() .

0

. .

private EditControl control;

protected void Page_Init(object sender, EventArgs e)
{
   control = (EditControl)LoadControl("EditControl.ascx");
   control.dataToEdit = dataObject;
   this.container.Controls.Add(control);
}

protected void Button_Click(object sender, EventArgs e)
{
   var dataToEdit = control.dataToEdit; 
}

(), ViewState. , dataToEdit - TextBox - ?

+2

Controls created dynamically must be added to the event Initor PreInitpage.

You must do this here because the control state is not yet loaded. If you add a control AFTER you are blank, since the page already fills the values โ€‹โ€‹of the control page at the beginning of the page life cycle.

Learn more about the page life cycle here.

0
source

Source: https://habr.com/ru/post/1751606/


All Articles