Object reference not set to an instance of an object
I am trying to write a simple user control to hold a cached HTML "Select" Box
This works fine if I drag the control onto the page directly (in which case I can't work out how to access the control's properties) but errors if I try and programmatically load it into a placeholder
A cut down version of how I am trying to do this is below...
Code:
using ShoppingCart_Net.Controls;
namespace ShoppingCart_Net.productdb
{
public class browser_home : System.Web.UI.Page
{
protected CachedListBox clbTypes = new CachedListBox();
private void Page_Load(object sender, System.EventArgs e)
{
string ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"].ToString();
phTypes.Controls.Add(clbTypes);
clbTypes.Query = "Select ProductTypes.ProductTypeID,ProductTypes.ProductTypeDescription From ProductTypes Order By ProductTypes.ProductTypeDescription";
clbTypes.TextField = "ProductTypeDescription";
clbTypes.ValueField = "ProductTypeID";
clbTypes.ConnectionString = ConnectionString;
}
}
}
The CachedListBox.ascx page just contains one line (apart from the directives) as below.
<asp:DropDownList id="lbCached" runat="server"></asp:DropDownList>
The (cut down) code behind for the user control is...
Code:
namespace ShoppingCart_Net.Controls
{
using System.Data.OleDb;
public class CachedListBox : System.Web.UI.UserControl
{
protected System.Web.UI.WebControls.DropDownList lbCached;
private string mQuery, mConnectionString, mTextField, mValueField;
private void Page_Load(object sender, System.EventArgs e)
{
if (! this.IsPostBack)
{
OleDbConnection objConn = new OleDbConnection(mConnectionString);
OleDbCommand objComm = new OleDbCommand(mQuery, objConn);
objConn.Open();
try
{
lbCached.DataTextField = mTextField;
lbCached.DataValueField = mValueField;
lbCached.DataSource = objComm.ExecuteReader();
lbCached.DataBind();
}
finally
{
objConn.Close();
}
}
}
public string Query
{
get
{
return mQuery;
}
set
{
mQuery = value;
}
}
//Other Properties omitted for conciseness
}
}
The Error occurs at the first use of lbCached in the Page_Load event above and is as follows...
"Exception Details: System.NullReferenceException: Object reference not set to an instance of an object."
Can anyone see what I am doing wrong?
Cheers!
Martin