Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

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

Posted on 2006-07-13
24
310 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
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 

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
 
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Google Directions API to Map URL -C#? 3 37
C# Gridview 1 47
Need help with a Crystal Report in my C#.Net application 2 26
Calculate number of nights between two dates 5 53
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

840 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