Very new to ASP, and I have what seems like a very simple question. I have the following code in the default.aspx.cs file:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateTime oneDayAgo = DateTime.Now.ToLocalTime().AddDays(-1);
String strOneDayAgo = oneDayAgo.ToString();
String queryString = "Select * from Computers Where whenCreated >= '" + strOneDayAgo + "' ORDER BY whenCreated DESC";
lblQueryUsed.Text = queryString;
DataSet ds = GetData(queryString);
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
All this works very well, but the problem is that the user clicks a link on this page to go to another page called Reports.aspx, the same Page_Load event is fired, and all the controls (lblQueryUsed, GridView1) for some reason The reason is set to NULL and I get an exception.
Why is the Page_Load event to load the default .aspx when I want to load Reports.aspx? Why are the controls null?
Thank you very much for your help.
EDIT: Here is the full code for this page, what else do you need?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;
using System.Data.SqlClient;
using Sorter;
using System.Data;
namespace AD_watcher_web_app
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateTime oneDayAgo = DateTime.Now.ToLocalTime().AddDays(-1);
String strOneDayAgo = oneDayAgo.ToString();
String queryString = "Select * from Computers Where whenCreated >= '" + strOneDayAgo + "' ORDER BY whenCreated DESC";
lblQueryUsed.Text = queryString;
DataSet ds = GetData(queryString);
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
protected void Label1_PreRender(object sender, EventArgs e)
{
lblCompCount.Text = GridView1.Rows.Count.ToString();
lblTimeRun.Text = DateTime.Now.ToLocalTime().ToString();
}
DataSet GetData(String queryString)
{
SqlConnectionStringBuilder conBuilder = new SqlConnectionStringBuilder();
conBuilder.DataSource = "dbsql01dev.llnl.gov";
conBuilder.InitialCatalog = "XloadDB";
conBuilder.IntegratedSecurity = true;
String connectionString = conBuilder.ConnectionString;
DataSet ds = new DataSet();
try
{
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
adapter.Fill(ds);
}
catch(Exception ex)
{
lblExceptions.Text = ex.ToString();
lblExceptions.Visible = true;
}
return ds;
}
}
}
source
share