C# – Pass data from a ASP.NET page to ASCX user controls loaded dynamically

ascxasp.net-ajaxccommunication

I'm developing an ASP.NET application with C# and Ajax.

I have a page that holds user controls loaded dynamically. I need to pass some data (integer values and some strings) to the user control that has been loaded dynamically.

Now I use Session to pass these values, but I think I can use another way; something like VIEWSTATE or hidden input.

What do you recommend me?

UPDATE:

The fact that I load the controls dynamically is important because controls are loaded on every postback, and I can't store any value on controls.

Best Answer

Create a property on your user control with the datatype of the data you want to pass to it, and populate it in your page on creation of the control.

public class myControl : Control
{
  ...
  public int myIntValue {get; set;}
  ...
}

In the code behind:

myControl ctrl = new myControl();
ctrl.myIntValue = 5;

You can also do this directly in markup:

<uc1:myControl ID="uc1" runat="server" myIntValue="5" />
Related Topic