0

I created a user control in ASP.net C# with a Dropdownlist in it (called LookupGrid below). Now in the main form , I want to set the data source for the Combobox, but I am getting NullExceptions when on the line that sets the datasource for the combobox

Code in the main web form :

LookupGrid droplist = new LookupGrid();
droplist.ID = field.Name;
RecordSet lookupvalues = inRecs.ServiceClient.WebServiceClient.GetInstance().GetLookup("CurrentNRS_Admit", Convert.ToInt64(Session["UserID"].ToString()), field);
droplist.SetData(lookupvalues.ToDataSet());

In the user control :

protected void Page_Load(object sender, EventArgs e)
{

}
public void SetData(DataSet dTLookupValues)
{
    DropDownList1.DataSource = dTLookupValues.Tables[0];
}

I am getting error:

Object reference not set to an instance of an object.

On this line:

DropDownList1.DataSource = dTLookupValues.Tables[0];

1 Answer 1

1

create property and set the data table from the public method. in page load you can bind the data

public DataTable MyData { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    DropDownList1.DataSource =MyData  ;
    DropDownList1.DataBind();
}

public void SetData(DataSet dTLookupValues)
{
    MyData  = dTLookupValues.Tables[0];
}

in your main page

   protected void Page_Load(object sender, EventArgs e)
    {
        var control = (LookupGrid )LoadControl("~/LookupGrid.ascx");
        control.SetData(lookupvalues.ToDataSet());
        Panel1.Controls.Add(control); //add control to your page or panel
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks , can you explain why is that?
read about asp.net page life cycle. server controls in the tree are created and initialized on page load, to set a property value of control, you need to have initialized control
Are you sure that's the only thing i need to do to initialize? Now I get the error on this line : DropDownList1.DataSource =MyData ;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.