Question

How can I make an object reference of a Literal that I have declared in the aspx page. Now I use it as ltlContents.Text = ..... but I need to make a reference of that ltlContents so I can use it in a static method the same way I use it with its .Text attribute.

I tried something like Literal ltl = ... but this is new for me, as it's different from the usual object referencing, as it comes from the front-end.

UPDATE: I want to use the ltlContents object in a static method like this: ltlContents.Text = valueFromSomeFunction, but the compiler gives me the following error: An object reference is required for the non-static field, method, or property _Default.ltlContents.

Was it helpful?

Solution

You need a reference to the control or the page where this control is sitting in. This page must be running though an actual lifecycle. So for example from a webmethod you cannot access a control.

However, then you can access this control even from a static method, which seems to be what you want:

public static void SetControlText(string controlID, string text) 
{ 
   Page page = HttpContext.Current.Handler as Page;
   if (page != null)
   {
      Control ctrl = FindControlRecursive(page, controlID);
      if(ctrl != null)
      {
          ITextControl txt = ctrl as ITextControl;
          if(txt != null)
              txt.Text = text;
      }
   }
}

public static Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id) return root;
    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null) return t;
    }
    return null;
}

Now this works from everywhere during the lifefycle of a page:

SetControlText("ltlContents", "Hello world");

OTHER TIPS

Since for every request a new object of your page is provided as response (their html). So it is not possible to do it.
Instead of using that literal to the function make function return a value from your function and use it. Or use the value of literal to function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top