开发者

Is SqlDataSource can be shared across different aspx page?

开发者 https://www.devze.com 2023-03-26 19:32 出处:网络
as开发者_StackOverflow中文版 the title said is SqlDataSource can be shared across different aspx page?

as开发者_StackOverflow中文版 the title said is SqlDataSource can be shared across different aspx page? i have exact same sqldatasource on multiple aspx page, is it possible to create one and shared for all the pages.

thanks


Sure. If you really mean shared, as in all pages use the same SqlDataSource, create a Master Page and put the data source in the master. In the codebehind, expose it as a property of the master. From there, you can reference it from any page that uses the Master.

Second option - create a base Page class:

public class MyPage : Page
{
      private SqlDataSource mDataSource;

      public override void OnLoad(EventArgs e)
      {
           base.OnLoad(e);
           // some code to init your data source - depending on your
           // implementation, this may need to be in OnInit instead
      }

      public SqlDataSource DataSource 
      { 
           get { return mDataSource; } 
      }
}

In this case, any time you create a new page, go to the code behind and change the declaration from implementing Page to MyPage. All pages that implement MyPage will have an SqlDataSource member, though each would have its own instance, so that's not really "sharing" the same SqlDataSource.

Either option gets you where you want to go I think.

UPDATE: Poster requested an example of exposing in as a property of the master:

Given a Master Page with the following:

<asp:SqlDataSource runat="server" ID="mDataSource" ... the rest of your properties .... />
<asp:ContentPlaceHolder runat="server" ID="MainContent"/>

In the code-behind for the master, define the property:

public class SiteMaster : System.Web.UI.MasterPage
{
    public SqlDataSource MasterDataSource
    {
         get { return mDataSource; }
    }

    // the rest of your master page's codebehind
}

In the pages you define for using your master page, add the following below the @Page declaration:

<%@ MasterPage VirtualPath="~/site.master"%>

Now, in the codebehind for that page, you can reference:

protected void Page_Load(object sender, EventArgs e)
{
     SqlDataSource ds = this.Master.MasterDataSource;
}

As long as you have as long as you have a <%@ MasterType VirtualPath="~/ PATH TO YOUR MASTER" %> in your aspx page, you can reference any properties you expose in the master.

Happy coding.

B


Controls are specific to pages. To share it across pages put it in a UserControl and then expose it through the public property of the UserControl.


If you mean the connection string, the answer is yes. You can put it in a public shared class.

If you mean the connection being open during several pages. No.

You should always close the connection ASAP to avoid memory leaks.

0

精彩评论

暂无评论...
验证码 换一张
取 消