c# - Passing DataContext to a User Control -


I have a page with a dataset:

  secure zero page_load (object sender , EventErgues e) {MyDifedDataContactsMyDataConnect = New MyDIFIEDDataContact (); }   

I want to pass this datacentext through user control:

  & lt;% @ Page language = "C #" MasterPageFile = "~ / Site 2. Mister" Inheritance = "WebApplication 3. Default"%> & Lt;% @ Register src = "inc / tabular.ascx" tag name = "tabular" tagprofix = "test"%> & Lt; ASP: Content ID = "Content1" content playholder ID = "contenthallsholder 1" runat = "server" & gt; & Lt; Trial: Tabular ID = "Tabular article" runat = "server" current page = "3" title = "article" /> & Lt; / ASP: Content & gt;   

How can I do this? Can I do this in page_load of any user control?

  Protected Zero Page_load (Object Sender, EventEurge E) {myCtx = mydatacont; This.setPreInfo (); This.getTableInfo (); This.setTableMeta (); }    

You can call it your UserControl . Datacontext are affordable for creating objects, so if you need access to the object then you can just add a new one

However, to answer your question directly You can share a HttpContext -scoped DataContext between all user controls by storing it in HttpContext. Item such as

  HttpContext.Items ["DataContextKey"] = New MyDataContext (); After that, you can start a field in your constructor like your control.  
  _dataContext = (MyDataContext) Context.Items [" DataContextKey "];   

DataContext A more elegant implementation of this approach (and other methods) for managing life cycle in general is a DataContextFactory class.

The method that will be most interesting to you:

  Fixed object GetWebRequestScopedDataContextInternal (type type, string key, string connection string) {object references; If (HttpContext.Current == faucet) {if (connectionString == zero) Reference = Activator.CreateInstance (type); Else context = Activator.CreateInstance (type, connectionString); Return reference; } // *** Create a unique key for web requests / references if (key == empty) key = "__WRSCDC_" + HttpContext.Current.GetHashCode (). ToString ("x") + Thread.CurrentContext.ContextID Wire(); Reference = HttpContext.Current.Items [Key]; If (reference == faucet) {if (connectionString == null) context = Activator.CreateInstance (type); Else context = Activator.CreateInstance (type, connectionString); If (reference! = Null) HTTPTP Tag Present. Item [key] = reference; } Refund Reference; }    

Comments