Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 327
  • Last Modified:

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); }
            }
    }
}
0
watherton
Asked:
watherton
  • 13
  • 9
  • 2
1 Solution
 
dstanley9Commented:
Then ddCardHolder is NULL.  Where does this variable get initialized?
0
 
wathertonAuthor Commented:
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
0
 
dstanley9Commented:
Not the dataset, ddCardHolder.  Accessing ddCardHolder.DataSource throws an exception because ddCardHolder is null.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
wathertonAuthor Commented:
sorry i'm not following, the code sets the drop down list with the dataset....
0
 
wathertonAuthor Commented:
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
0
 
levyukCommented:
You haven't created ddCardHolder. It doesn't exist
0
 
dstanley9Commented:
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.
0
 
dstanley9Commented:
Duhh.  You're using ASP.NET 2.0 and partial classes.  There is no "Designer Generated" code
0
 
wathertonAuthor Commented:
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.
0
 
dstanley9Commented:
Where is SelectedClientID being set?  It's possible that the Set accessor is being called before the drop-down is being initialized.
0
 
wathertonAuthor Commented:
dstanley9 - correct
0
 
wathertonAuthor Commented:
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
0
 
dstanley9Commented:
What if you just set the clientID value in the Set accessor and let the drop-down build in Page_Load?
0
 
wathertonAuthor Commented:
can we pick this up in the morning chaps, I need an early start?

Wayne
0
 
wathertonAuthor Commented:
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
0
 
levyukCommented:
What is ddCardHolder? Is it a control on your form?
0
 
wathertonAuthor Commented:
no it is a asp:DropDownList on the CardHolderList user control
0
 
dstanley9Commented:
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.
0
 
wathertonAuthor Commented:
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
0
 
dstanley9Commented:
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;
       }
       
    }      
0
 
wathertonAuthor Commented:
hi dstanley,

when I compile i get a message telling me that the ClientChangedEventArgs does not exist
0
 
wathertonAuthor Commented:
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
0
 
dstanley9Commented:
If you run it in the debugger does the ClientChangedHandler method execute?  What about the SelectedClientID set accessor and BuildCardHolders?
0
 
wathertonAuthor Commented:
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.

http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_21921005.html
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 13
  • 9
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now