Solved

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

Posted on 2006-07-13
24
302 Views
Last Modified: 2010-04-16
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
Comment
Question by:watherton
  • 13
  • 9
  • 2
24 Comments
 
LVL 25

Expert Comment

by:dstanley9
ID: 17103849
Then ddCardHolder is NULL.  Where does this variable get initialized?
0
 

Author Comment

by:watherton
ID: 17103923
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
 
LVL 25

Expert Comment

by:dstanley9
ID: 17103942
Not the dataset, ddCardHolder.  Accessing ddCardHolder.DataSource throws an exception because ddCardHolder is null.
0
 

Author Comment

by:watherton
ID: 17103969
sorry i'm not following, the code sets the drop down list with the dataset....
0
 

Author Comment

by:watherton
ID: 17103992
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
 
LVL 7

Expert Comment

by:levyuk
ID: 17104003
You haven't created ddCardHolder. It doesn't exist
0
 
LVL 25

Expert Comment

by:dstanley9
ID: 17104004
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
 
LVL 25

Expert Comment

by:dstanley9
ID: 17104031
Duhh.  You're using ASP.NET 2.0 and partial classes.  There is no "Designer Generated" code
0
 

Author Comment

by:watherton
ID: 17104037
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
 
LVL 25

Expert Comment

by:dstanley9
ID: 17104043
Where is SelectedClientID being set?  It's possible that the Set accessor is being called before the drop-down is being initialized.
0
 

Author Comment

by:watherton
ID: 17104050
dstanley9 - correct
0
 

Author Comment

by:watherton
ID: 17104068
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 25

Expert Comment

by:dstanley9
ID: 17104073
What if you just set the clientID value in the Set accessor and let the drop-down build in Page_Load?
0
 

Author Comment

by:watherton
ID: 17104083
can we pick this up in the morning chaps, I need an early start?

Wayne
0
 

Author Comment

by:watherton
ID: 17106144
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
 
LVL 7

Expert Comment

by:levyuk
ID: 17106806
What is ddCardHolder? Is it a control on your form?
0
 

Author Comment

by:watherton
ID: 17106896
no it is a asp:DropDownList on the CardHolderList user control
0
 
LVL 25

Expert Comment

by:dstanley9
ID: 17108136
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
 

Author Comment

by:watherton
ID: 17108445
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
 
LVL 25

Expert Comment

by:dstanley9
ID: 17108558
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
 

Author Comment

by:watherton
ID: 17113939
hi dstanley,

when I compile i get a message telling me that the ClientChangedEventArgs does not exist
0
 

Author Comment

by:watherton
ID: 17114124
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
 
LVL 25

Accepted Solution

by:
dstanley9 earned 200 total points
ID: 17122068
If you run it in the debugger does the ClientChangedHandler method execute?  What about the SelectedClientID set accessor and BuildCardHolders?
0
 

Author Comment

by:watherton
ID: 17122881
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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now