0

I am using asp.net forms. There is a Page_Load event,but is there an end event?

I have a linq datacontext created on pageload and I would like to dispose it when I am done.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user2043533
  • 731
  • 3
  • 9
  • 23
  • I presume you're using LINQ to SQL? – John Saunders Mar 15 '13 at 19:35
  • If you're using LinqToSQL then you should not have a context created on Page_Load. You should wrap context in using {} statement, put them in a Data Access Layer, and access methods from the Data Access Layer within your ASP.net page as needed. – Dmitriy Khaykin Mar 15 '13 at 21:50

3 Answers3

5

You should probably do it on Page_Unload Event is the last event in page life cycle. For more on page events check out this.

Emmanuel N
  • 7,350
  • 2
  • 26
  • 36
1

As Emmanuel N stated, there is Page_Unload event. However, if you use using, you do not need to worry about disposing DataContext.

Here is an example.

protected void buttonSearch_Click(object sender, EventArgs e)
{
  using (var context = new NorthwindDataContext())
  {
    var customers =
      from c in context.Customers
      select c;

    gridViewCustomers.DataSource = customers;
    gridViewCustomers.DataBind();
  }
}

Using is better than Dispose.

Community
  • 1
  • 1
Win
  • 61,100
  • 13
  • 102
  • 181
0

By the way if you are using Entity Framework, you don't have to dispose DbContext: the default behaviour is to open connection when needed and close it when done (more details).

Alexander Tsvetkov
  • 1,649
  • 14
  • 24