views:

41

answers:

2

Hi! I have some control. I add one instance of this control to every Page in OnInit event and I want to access this control in other places in this way: Sample.Current

public class Sample : Control
{
    public static Sample Current
    {
        get
        {
            // ???
        }
    }
}

Can you tell me what is the best way to do this property implementation?

A: 

I don't think it would be realistically possible to use a true static instance of the control since controls are associated with a page and normally have state.

It should be possible to have a 'singleton' per request though. Perhaps something like this:

https://www.west-wind.com/Weblog/posts/417588.aspx

James
A: 

Hi,
It would be good to have a bit more detail - what is this class' purpose? But I'll attempt to help anyway:

You'll be able to access that control from within code on the page , if it's referenced in the code and not added dynamically somehow at runtime. ie if it's a variable of the page declared like:

Sample ctrl = new Sample();

Then later you can reference it using ctrl.Current in your code.

FYI - if you want a place to reference classes and variables for a page's lifecycle, you may want to check out HttpContext.Current.Items http://www.mikeduncan.com/3-hot-uses-for-httpcontextcurrentitems-they-wont-tell-you-about/ It's like a session bag that only exists for a single page request - for example if you have a class that holds information about a user that you need to access many times from many different controls on the page, you could just stick that class into the Items collection and then reference it from any code that runs on your page.

HTH,
Lance

Lanceomagnifico