Link to home
Start Free TrialLog in
Avatar of watherton
watherton

asked on

object referece not set to an instance of an object - user control

I get the above error when trying to add a dataset to my drop down list within a user control


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using CapitalIncentives.Card;


namespace CapitalIncentives.UserInterface
{
    public partial class CardHolderList : System.Web.UI.UserControl
    {
        public DataSet cardHolderDetails;

        public int cardHolderID;

        public int clientID;

       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
               // int test = (UserControl)ucClientList.clientID;

               // UserControl ucClientList = (UserControl)Page.FindControl("ClientList");
               
               // int test = int.Parse(((DropDownList)Page.FindControl("ClientList:ddClients")).SelectedItem.Value);

                if (clientID != 0)
                {
                    BuildCardHolders(clientID);
                }
            }
           
        }
     
        public void BuildCardHolders(int id)
        {
           
                using (CardHolderManagement cardHolderManagement = new CardHolderManagement())
                {

                    cardHolderManagement.GetClientCardHolders(clientID, out cardHolderDetails);

                    //Store the retrieved card holder details in session.

                    if (cardHolderDetails.Tables[0].Rows.Count > 0)
                    {
                        if (cardHolderDetails != null)
                        {
                            DataColumn newColumn = new DataColumn();

                            newColumn.ColumnName = "fullName";

                            newColumn.DataType = System.Type.GetType("System.String");

                            newColumn.Expression = "FirstName+'  '+LastName";

                            cardHolderDetails.Tables[0].Columns.Add(newColumn);

  /////////////////////////                          ddCardHolder.DataSource = cardHolderDetails;   ///////////////////////////// This is the line where the above error occurs
                            ddCardHolder.DataTextField = "fullName";
                            ddCardHolder.DataValueField = "CardHolderID";
                            ddCardHolder.DataBind();
                            ddCardHolder.Items.Insert(0, new ListItem("--Please select--", "0"));
                            ddCardHolder.Visible = true;
                        }
                    }

                    // Set the current card holder dataset in session, so that it can be used
                    // when displaying the card holder details.
                    Session["cardHolders"] = cardHolderDetails;

                    // Set the clientID to session variable, so that it can be used later on.
                    Session["clientID"] = clientID;

                }
            }

            public void CardHolder_Changed(Object sender, EventArgs e)
            {
                cardHolderID = int.Parse(ddCardHolder.SelectedItem.Value);
            }

            public int SelectedCardHolder
            {
                get { return int.Parse(ddCardHolder.SelectedItem.Value); }
            }

            public int CardHolderChanged
            {
                get { return cardHolderID; }
                set { cardHolderID = value; }
            }

            public int CardHolderID
            {
                get { return cardHolderID; }
                set { cardHolderID = value; }
            }

            public int SelectedClientID
            {
                get { return clientID; }
                set { clientID = value;
                      BuildCardHolders(clientID); }
            }
    }
}
Avatar of dstanley9
dstanley9

Then ddCardHolder is NULL.  Where does this variable get initialized?
Avatar of watherton

ASKER

how can it be null. There are several checks to see if the dataset is null before assigning the dataset to the drop down

If(CardHolderDetails.Tables[0].Rows.Count > 0)
{

    if (cardHolderDetails != null)

    {

       ..........


    }

}

if the dataset was null then setting the datasource would not take place
Not the dataset, ddCardHolder.  Accessing ddCardHolder.DataSource throws an exception because ddCardHolder is null.
sorry i'm not following, the code sets the drop down list with the dataset....
are you trying to say that because I am calling the buildCardholders method from the property, that the page has not loaded the ddcardholder to the screen. If so then how would I go about passing in my value to this method?

Wayne
You haven't created ddCardHolder. It doesn't exist
I'm assuming you've left out the "Designer Generated" code from your post, because I don't see the ddCardHolder variable declared or initialized.  I'm also assuming it's the ID of a control in your UserControl.  

Run it in debugger and see what the value of ddCardHolder is at that line.
Duhh.  You're using ASP.NET 2.0 and partial classes.  There is no "Designer Generated" code
yep, the dd list has not been rendered to the screen when i call the BuildDropDown from within the property. So how do I then call this method.

the property value is populated from another usercontol, I need to then take this property value and build my cardholder drop down.
Where is SelectedClientID being set?  It's possible that the Set accessor is being called before the drop-down is being initialized.
dstanley9 - correct
dstanley9 - correct again. I need away of using the first controls index_changed method to fire off the builddropdown method in the second user control
What if you just set the clientID value in the Set accessor and let the drop-down build in Page_Load?
can we pick this up in the morning chaps, I need an early start?

Wayne
morning guys.

Ok, I think some code may help explain.

ClientList.ascx
----------------

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using CapitalIncentives.Clients;


namespace CapitalIncentives.UserInterface
{
    public partial class ClientList : System.Web.UI.UserControl
    {
        public DataSet clients;

        public int clientID;

        protected string[] validationErrors = null;

        private ArrayList errorList = new ArrayList(1);

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BuildClientsDropDown();
            }
        }

        public void BuildClientsDropDown()
        {
            try
            {
                using (CapitalIncentives.Clients.ClientManagement clientManagement = new CapitalIncentives.Clients.ClientManagement())
                {

                    clientManagement.GetCurrentClientList(out clients);
                    if (clients != null)
                    {
                        DataColumn newColumn = new DataColumn();

                        newColumn.ColumnName = "fullClient";

                        newColumn.DataType = System.Type.GetType("System.String");

                        newColumn.Expression = "ClientNumber+' -- '+ClientName";

                        clients.Tables[0].Columns.Add(newColumn);

                        ddClients.DataSource = clients;
                        ddClients.DataTextField = "fullClient";
                        ddClients.DataValueField = "ClientID";
                        ddClients.DataBind();
                        ddClients.Items.Insert(0, new ListItem("--Please select--", "0"));
                    }

                    // Check if there are any clients registered
                    if (clients.Tables[0].Rows.Count == 0)
                    {
                        // If the dataset is equal 0, then disable form content and display message.
                        errorList.Add(@"There are no clients." + System.Environment.NewLine);
                        validationErrors = (string[])errorList.ToArray(typeof(string));
                    }
                }
            }
            catch (Exception error)
            {
                validationErrors = (string[])errorList.ToArray(typeof(string));
                errorList.Add(@"There has been a problem populating the client drop down list." + error.Message);
            }
        }

        public void Client_Changed(Object sender, EventArgs e)
        {
          clientID = int.Parse(ddClients.SelectedItem.Value);

          CapitalIncentives.UserInterface.CardHolderList objList = new CapitalIncentives.UserInterface.CardHolderList();

          objList.SelectedClientID = clientID;
                 
        }
       
    }

}



CardHolderList.ascx
------------------------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using CapitalIncentives.Card;


namespace CapitalIncentives.UserInterface
{
    public partial class CardHolderList : System.Web.UI.UserControl
    {
        public DataSet cardHolderDetails;

        public int cardHolderID;

        protected int clientID;

       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
             
                if (clientID != 0)
                {
                    BuildCardHolders(clientID);
                }
            }
       
           
        }
     
        public void BuildCardHolders(int id)
        {
           
                using (CardHolderManagement cardHolderManagement = new CardHolderManagement())
                {

                    cardHolderManagement.GetClientCardHolders(clientID, out cardHolderDetails);

                    //Store the retrieved card holder details in session.

                    if (cardHolderDetails.Tables[0].Rows.Count > 0)
                    {
                        if (cardHolderDetails != null)
                        {
                            DataColumn newColumn = new DataColumn();

                            newColumn.ColumnName = "fullName";

                            newColumn.DataType = System.Type.GetType("System.String");

                            newColumn.Expression = "FirstName+'  '+LastName";

                            cardHolderDetails.Tables[0].Columns.Add(newColumn);

                            ddCardHolder.DataSource = cardHolderDetails;
                            ddCardHolder.DataTextField = "fullName";
                            ddCardHolder.DataValueField = "CardHolderID";
                            ddCardHolder.DataBind();
                            ddCardHolder.Items.Insert(0, new ListItem("--Please select--", "0"));
                            ddCardHolder.Visible = true;
                        }
                    }

                    // Set the current card holder dataset in session, so that it can be used
                    // when displaying the card holder details.
                    Session["cardHolders"] = cardHolderDetails;

                    // Set the clientID to session variable, so that it can be used later on.
                    Session["clientID"] = clientID;

                }
            }

            public void CardHolder_Changed(Object sender, EventArgs e)
            {
                cardHolderID = int.Parse(ddCardHolder.SelectedItem.Value);
            }

            public int SelectedCardHolder
            {
                get { return int.Parse(ddCardHolder.SelectedItem.Value); }
            }

            public int CardHolderChanged
            {
                get { return cardHolderID; }
                set { cardHolderID = value; }
            }

            public int CardHolderID
            {
                get { return cardHolderID; }
                set { cardHolderID = value; }
            }

            public int SelectedClientID
            {
                get { return clientID; }
                set { clientID = value;
                     BuildCardHolders(clientID); }
            }
    }
}


the public property SelectedClientID fires off the BuildCardHolders with the ClientID pass to it from the Client user control but because the Card Holder drop down list has not been drawn to the screen yet, it does not exist.

So the question is, how do I pass over the int value I need to populate the card holder drop down from the client user control???????


I've increased the points so that I can spread them out, as there were some great responses last night - cheers
What is ddCardHolder? Is it a control on your form?
no it is a asp:DropDownList on the CardHolderList user control
I'm not sure you can communicate between user controls this way (it may be possible, but I'm not certain) because the page controls the lifecycle of the controls. Creating an instance in one control will not give you the instance that is rendered on the page.  

Even if you can, you're tying the two controls together, which is not the best design practice.  I would create a public event  on the ClientList  control to signify a change in the selected client, then let the containing control (or the page) respond to that event and make the appropriate change to the CardHolderList control.  

If these two controls are frequently used together, I would package them into one UserControl and use events to let the parent UserControl handle the communication between the two.
sounds like a plan, don't suppose you have any asp 2.0 c# examples, i need this one sorted asp as I have been on it for two days now.

Cheers

Wayne
Here's a start, no promises or warranties ;)


namespace CapitalIncentives.UserInterface
{
    public partial class ClientList : System.Web.UI.UserControl
    {

      // Add this:
      public event EventHandler<ClientChangedEventArgs> ClientChanged;

      protected virtual void OnClientChanged(ClientChangedEventArgs args)
      {
          EventHandler<ClientChangedEventArgs> handler = ClientChanged;
          if (handler != null)
          {
              handler(this, args);
          }
      }

      ...

        // Change This:
        public void Client_Changed(Object sender, EventArgs e)
        {
          clientID = int.Parse(ddClients.SelectedItem.Value);

          OnClientChanged(new ClientChangedEventArgs(clientID);
                 
        }
    }

    public class ClientChangedEventArgs : EventArgs
    {
        public ClientChangedEventArgs(int clientID)
        {
            this._ClientID = clientID;
        }
 
        private int _ClientID;

        public int ClientID
        {
            get
           {
                return this._ClientID;
            }
        }
    }

}  


    public partial class ParentControl : System.Web.UI.UserControl
    {
       // Add two usercontrols in designer : clientList1 and cardHolderList1, for example:
       
       clientList1.ClientChanged += ClientChangedHandler;
       

       void ClientChangedHandler(object sender, ClientChangedEventArgs args)
       {
           cardHolderList1.SelectedClientID = args.ClientID;
       }
       
    }      
hi dstanley,

when I compile i get a message telling me that the ClientChangedEventArgs does not exist
ok, this was being caused because i needed to fully qualify the ClientChangedEventArgs to 'CapitalIncentives.UserInterface.ClientChangedEventArgs' but this is not populating the card holder drop down within the CardHolder usercontrol
ASKER CERTIFIED SOLUTION
Avatar of dstanley9
dstanley9

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
hi dstanley9, thank you for responding, I am going to award you the points for this q as you have been the only one who has been helping, however, because this post was becoming to busy I've posted again with a few updates, please see link to check out where I am up to on this.

https://www.experts-exchange.com/questions/21921005/Almost-there-with-my-controls-but-need-some-help.html