Pass variables and access methods of User Control from CodeBehind

So I have a function renderWidget() in default.aspx.cs. The idea of this is to add a User Control to a page.

public void renderWidget(string data) {
    Control ctrl = Page.LoadControl("/widgets/widget.ascx");

This all works fine, lovely jubbly. Now in the other end, at the User Control, I have the following code in widget.ascx.cs:

public class WidgetControl : System.Web.UI.UserControl
    public string testString = "";
    public void test() {


The problem arises when I try to access either of the properties in the User Control. When I try to add ctrl.test() or ctrl.testString = "test" to default.aspx.cs, I get the error "'System.Web.UI.Control' does not contain a definition for 'test'". I feel like there's probably something very basic I'm missing here.

Any help appreciated, thanks!


You have to cast to the correct type:

WidgetControl widget = (WidgetControl)ctrl;
widget.testString = "Foo";

LoadControl returns Control and not the actual type of your UserControl.

You need to cast your instance to WidgetControl.

Need Your Help

JQuery Animate Background Image on Y-axis

jquery jquery-animate

I seem to experiencing a problem with the JQuery animation. I can animate the background image in the positive direction, but not in the negative direction. Any suggestions as to how to remedy this?

php if else show statement - date dependent like. show if date=Dec. 2, 2010 or less than?

php date if-statement

I updated my photo-gallery framework recently. But I still need the old 'javascript files' in stories older than a certain date, eg: Dec. 2, 2010. (stories are in CMS/dynamic)