Solved

Object reference not set to an instance of an object.

Posted on 2009-05-14
5
1,327 Views
Last Modified: 2012-05-08
Hello,

I researched the existing "Object reference not set to an instance of an object." items on Experts-Exchange.

I'm not skilled enough to translate the existing issues to my scenario. So if you have comments about that please write them in Notepad, save the file and delete it.

This Object reference not set to an instance of an object. has the specific error:

[NullReferenceException: Object reference not set to an instance of an object.]

I believe my issue is with (line 430) "lblThankYou.Text" and it is null.

Regardless of what I think, I appreciate direct assistance fixing the code an getting the page working again. Learning is secondary for me.

Thank you,

Christopher
YELLOW PAGE CONTENT

****************************

Object reference not set to an instance of an object. 

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
 

Source Error: 
 
 

Line 428:            body += "messagelabelhere: " + ddlitemhere.SelectedValue + "\r\r";

Line 429:            body += "messagelabelhere: " + txtnaswerhere.Text + "\r\r";

Line 430:            lblThankYou.Text = "<img align='right' src=URLhere.com/imagenamehere.jpg' height='200' width='154' alt='alttaghere' " +

Line 431:                " style='border:1px solid silver; margin-left:20px;' />" +

Line 432:                "<h3>heading message for thank you page here</h3>" +

 
 

Source File: ...URLhere\Controls\filenamehere.ascx.cs    Line: 430 
 

Stack Trace: 
 
 

[NullReferenceException: Object reference not set to an instance of an object.]

   Controls_filenamehere.btnSubmit_Click(Object sender, EventArgs e) in filelocationandurlhere... .ascx.cs:430

   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111

   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110

   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10

   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13

   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36

   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
 

ACTUAL ASCX PAGE CODE

****************************
 

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;
 

public partial class Controls_filenamehere : System.Web.UI.UserControl

{

    public string TraceCat = "form_filenamehere.ascx.cs";

    public string ThisThing;
 

    protected void Page_Load(object sender, EventArgs e)

    {

        string OPTION;
 

        OPTION = "ThisOption";
 

        Trace.Warn(TraceCat, "OPTION: " + OPTION);
 

        ThisThing = lblHdnplacething.Text;
 

        try

        {

            if (!Page.IsPostBack)

            {

                // Get the URL of where this page is

                ThisThing = Request.Url.ToString();

            }

            Trace.Warn(TraceCat, "ThisThing: " + ThisThing);
 

            if (!Request.Url.ToString().Contains("thisotherthing"))

            {

                if (!Page.IsPostBack)

                {

                    // The page was reached via the regionthing ddl

                    pnlRegionOption.Visible = true;

                    ddlRegionThing.Items.Clear();

                    ddlRegionThing.Items.Add(new ListItem("Select a placething", ""));

                    ddlRegionThing.Items.Add(new ListItem("AAA", "AAA"));

                    ddlRegionThing.Items.Add(new ListItem("BBB", "BBB"));

                    ddlRegionThing.Items.Add(new ListItem("CCC", "CCC"));

                    ddlRegionThing.Items.Add(new ListItem("DDD", "DDD"));

                    ddlRegionThing.Items.Add(new ListItem("EEE", "EEE"));

                }

            }

            else

            {

                // Get the name of the placething you are on

                if (SiteMap.CurrentNode.Url.Contains("/thisotherthing/"))

                {

                    // The contact page was reached via the regionthing ddl

                    pnlRegionOption.Visible = false;
 

                    pnlddlreason.Visible = true;
 

                    ThisThing = SiteMap.CurrentNode.Url.ToString();

                    ThisThing = ThisThing.Replace("~/thisotherthing", "");

                    ThisThing = ThisThing.Remove(0, 1);

                    ThisThing = ThisThing.Replace(".aspx", "");

                    ThisThing = ThisThing.Substring(0, ThisThing.IndexOf("/"));

                }

            }
 

            Trace.Warn(TraceCat, "ThisThing: " + ThisThing);

        }

        catch

        {

            // Do nothing

        }
 

        try

        {
 
 

skipping, skipping, skipping
 
 
 

    protected void btnSubmit_Click(object sender, EventArgs e)

    {

        // Make sure input is valid

        if (!Page.IsValid)

        {

            return;

        }
 

        string toEmailAddress;
 

        string ThisThing;
 
 

        if (SiteMap.CurrentNode.Url.Contains("/thisotherthing/"))

        {

            // The contact page was reached via the regional site show placething drop down

            ThisThing = SiteMap.CurrentNode.Url.ToString();

            ThisThing = ThisThing.Replace("~/thisotherthing", "");

            ThisThing = ThisThing.Remove(0, 1);

            ThisThing = ThisThing.Replace(".aspx", "");

            ThisThing = ThisThing.Substring(0, ThisThing.IndexOf("/"));
 

        }

        else

        {

            ThisThing = ddlRegionThing.SelectedItem.Value;

        }

        // EMAIL FOR DEBUG PURPOSES

        toEmailAddress = "me@ourdomain.com";
 

        // Uncomment when you go LIVE

        //toEmailAddress = lblHiddenEmail.Text;

        Trace.Warn("lblHiddenEmail.Text: " + lblHiddenEmail.Text);

        Trace.Warn("toEmailAddress: " + toEmailAddress);
 

        // Who the emial appears to be from

        string fromEmailAddress = txtEmail.Text;
 

        // Email subject

        string subject = "";
 

        // Email body

        string body = "";

        body += "Name: " + txtFname.Text + " " + txtLname.Text + "\r";

        body += "Email: " + txtEmail.Text + "\r";

        body += "Best time to contact: " + txtBestTime.Text + "\r";

        if (txtPartB.Text != "")

        {

            body += "Phone: " + txtPartA.Text + "-" + txtPartB.Text + "-" + txtPartC.Text + " Ext:" + txtExt.Text + "\r\r";

        }

        else

        {

            body += "Phone: NA\r\r";

        }

        body += "Reason for this form submission: " + ddlReason.SelectedItem.Text;

        body += "\r\r";
 

        #region // ThisOption message

        if (ddlReason.SelectedValue == "ThisOption")

        {

            subject = "ThisItemHere";

            lblHiddenSubject.Text = "ThisItemHere";
 

	 body += "messagelabelhere: " + ddlitemhere.SelectedValue + "\r\r";

	body += "messagelabelhere: " + txtnaswerhere.Text + "\r\r";

	 lblThankYou.Text = "<img align='right' src=URLhere.com/imagenamehere.jpg' height='200' width='154' alt='alttaghere' " +

	" style='border:1px solid silver; margin-left:20px;' />" +

	 "<h3>heading message for thank you page here</h3>" +
 

etc...

Open in new window

0
Comment
Question by:celler_wellbridge
  • 3
  • 2
5 Comments
 
LVL 2

Accepted Solution

by:
IndianHero2001 earned 500 total points
ID: 24389132
You have not pasted the line with error in total.

There is still something after that + .. Paste it too so we can find the bug. So far, everything looks ok.
lblThankYou.Text = "<img align='right' src=URLhere.com/imagenamehere.jpg' height='200' width='154' alt='alttaghere' " +

        " style='border:1px solid silver; margin-left:20px;' />" +

         "<h3>heading message for thank you page here</h3>" +

Open in new window

0
 

Author Comment

by:celler_wellbridge
ID: 24390008
Thank you, here is the page code.

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;

public partial class Controls_filenamehere : System.Web.UI.UserControl
{
    public string TraceCat = "form_filenamehere.ascx.cs";
    public string ThisThing;

    protected void Page_Load(object sender, EventArgs e)
    {
        string OPTION;

        OPTION = "ThisOption";

        Trace.Warn(TraceCat, "OPTION: " + OPTION);

        ThisThing = lblHdnplacething.Text;

        try
        {
            if (!Page.IsPostBack)
            {
                // Get the URL of where this page is
                ThisThing = Request.Url.ToString();
            }
            Trace.Warn(TraceCat, "ThisThing: " + ThisThing);

            if (!Request.Url.ToString().Contains("thisotherthing"))
            {
                if (!Page.IsPostBack)
                {
                    // The page was reached via the regionthing ddl
                    pnlRegionOption.Visible = true;
                    ddlRegionThing.Items.Clear();
                    ddlRegionThing.Items.Add(new ListItem("Select a placething", ""));
                    ddlRegionThing.Items.Add(new ListItem("AAA", "AAA"));
                    ddlRegionThing.Items.Add(new ListItem("BBB", "BBB"));
                    ddlRegionThing.Items.Add(new ListItem("CCC", "CCC"));
                    ddlRegionThing.Items.Add(new ListItem("DDD", "DDD"));
                    ddlRegionThing.Items.Add(new ListItem("EEE", "EEE"));
                }
            }
            else
            {
                // Get the name of the placething you are on
                if (SiteMap.CurrentNode.Url.Contains("/thisotherthing/"))
                {
                    // The contact page was reached via the regionthing ddl
                    pnlRegionOption.Visible = false;

                    pnlddlreason.Visible = true;

                    ThisThing = SiteMap.CurrentNode.Url.ToString();
                    ThisThing = ThisThing.Replace("~/thisotherthing", "");
                    ThisThing = ThisThing.Remove(0, 1);
                    ThisThing = ThisThing.Replace(".aspx", "");
                    ThisThing = ThisThing.Substring(0, ThisThing.IndexOf("/"));
                }
            }

            Trace.Warn(TraceCat, "ThisThing: " + ThisThing);
        }
        catch
        {
            // Do nothing
        }

        try
        {


skipping, skipping, skipping



    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        // Make sure input is valid
        if (!Page.IsValid)
        {
            return;
        }

        string toEmailAddress;

        string ThisThing;


        if (SiteMap.CurrentNode.Url.Contains("/thisotherthing/"))
        {
            // The contact page was reached via the regional site show placething drop down
            ThisThing = SiteMap.CurrentNode.Url.ToString();
            ThisThing = ThisThing.Replace("~/thisotherthing", "");
            ThisThing = ThisThing.Remove(0, 1);
            ThisThing = ThisThing.Replace(".aspx", "");
            ThisThing = ThisThing.Substring(0, ThisThing.IndexOf("/"));

        }
        else
        {
            ThisThing = ddlRegionThing.SelectedItem.Value;
        }
        // EMAIL FOR DEBUG PURPOSES
        toEmailAddress = "me@ourdomain.com";

        // Uncomment when you go LIVE
        //toEmailAddress = lblHiddenEmail.Text;
        Trace.Warn("lblHiddenEmail.Text: " + lblHiddenEmail.Text);
        Trace.Warn("toEmailAddress: " + toEmailAddress);

        // Who the emial appears to be from
        string fromEmailAddress = txtEmail.Text;

        // Email subject
        string subject = "";

        // Email body
        string body = "";
        body += "Name: " + txtFname.Text + " " + txtLname.Text + "\r";
        body += "Email: " + txtEmail.Text + "\r";
        body += "Best time to contact: " + txtBestTime.Text + "\r";
        if (txtPartB.Text != "")
        {
            body += "Phone: " + txtPartA.Text + "-" + txtPartB.Text + "-" + txtPartC.Text + " Ext:" + txtExt.Text + "\r\r";
        }
        else
        {
            body += "Phone: NA\r\r";
        }
        body += "Reason for this form submission: " + ddlReason.SelectedItem.Text;
        body += "\r\r";

        #region // ThisOption message
        if (ddlReason.SelectedValue == "ThisOption")
        {
            subject = "ThisItemHere";
            lblHiddenSubject.Text = "ThisItemHere";

       body += "messagelabelhere: " + ddlitemhere.SelectedValue + "\r\r";
      body += "messagelabelhere: " + txtnaswerhere.Text + "\r\r";
       lblThankYou.Text = "<img align='right' src=URLhere.com/imagenamehere.jpg' height='200' width='154' alt='alttaghere' " +
      " style='border:1px solid silver; margin-left:20px;' />" +
       "<h3>heading message for thank you page here</h3>" +
                "And more message.<br/><br/> " +
                "And more message";
        }
        #endregion

        System.Net.Mail.MailMessage theMessage = new System.Net.Mail.MailMessage();
        theMessage.From = new System.Net.Mail.MailAddress(fromEmailAddress);
        theMessage.To.Add(new System.Net.Mail.MailAddress(toEmailAddress));
        string BCCEmailAddress = ConfigurationManager.AppSettings["BCCEmail"].ToString();
        if (BCCEmailAddress != null && BCCEmailAddress != "")
        {
            theMessage.Bcc.Add(new System.Net.Mail.MailAddress(BCCEmailAddress));
        }

        theMessage.Subject = subject;
        theMessage.Body = body;
        theMessage.IsBodyHtml = false;

        System.Net.Mail.SmtpClient theClient = new System.Net.Mail.SmtpClient();
        theClient.Host = ConfigurationManager.AppSettings["SmtpServer"];
        theClient.Send(theMessage);

        HideAllForms();

        pnlOPTION.Visible = false;
        pnlMainForm.Visible = false;
        btnSubmit.Visible = false;
        pnlThank.Visible = true;

        // Send the Thank You message to
        SendToCustomer(txtEmail.Text, toEmailAddress);
    }


    protected void SendToCustomer(string email, string FromEmail)
    {
        try
        {

            System.Net.Mail.MailMessage theMessage = new System.Net.Mail.MailMessage();
            theMessage.From = new System.Net.Mail.MailAddress(FromEmail);
            theMessage.To.Add(new System.Net.Mail.MailAddress(email));
            string BCCEmailAddress = ConfigurationManager.AppSettings["BCCEmail"].ToString();
            if (BCCEmailAddress != null && BCCEmailAddress != "")
            {
                theMessage.Bcc.Add(new System.Net.Mail.MailAddress(BCCEmailAddress));
            }

            theMessage.Subject = lblHiddenSubject.Text;
            theMessage.Body = lblThankYou.Text;
            theMessage.IsBodyHtml = true;

            System.Net.Mail.SmtpClient theClient = new System.Net.Mail.SmtpClient();
            theClient.Host = ConfigurationManager.AppSettings["SmtpServer"];
            theClient.Send(theMessage);
        }
        catch
        {
            // Email failed
        }

    }



    protected void ddlReason_SelectedIndexChanged(object sender, EventArgs e)
    {
        HideAllForms();

        if (pnlRegionOption.Visible == true)
        {
            Trace.Warn("ddlRegionalthing.SelectedValue.ToString() " + ddlRegionalthing.SelectedValue.ToString());
            //lblHdnthing.Text = ddlRegionalthing.SelectedValue.ToString();
            //placething = lblHdnthing.Text;
            placething = ddlRegionalthing.SelectedValue.ToString();
        }

        if (ddlReason.SelectedValue != "")
        {
            switch (ddlReason.SelectedValue)
            {
                case "filenamehere":
                    pnlfilenamehere.Visible = true;
                    pnlOPTION.Visible = true;
                    imgOPTION.ImageUrl = "~/Images/Contact/OPTION3.gif";
                    // Set Thank You message                  
                    lblThankYou.Text = "Thank you for your interest in our thing. We look forward to responding to your inquiry within 24 hours. If you would like to get started more quickly call the thing manager at " + ConfigurationManager.AppSettings["thingPhone" + placething].ToString() +
                        " or visit us at:<br><br>" +
                        ConfigurationManager.AppSettings["thingAddress" + placething].ToString() + "<br>" +
                        ConfigurationManager.AppSettings["thingCity" + placething].ToString() + ", " +
                        ConfigurationManager.AppSettings["thingState" + placething].ToString() + " " +
                        ConfigurationManager.AppSettings["thingZip" + placething].ToString() + "<br><br>" +
                        ConfigurationManager.AppSettings["thingName" + placething].ToString() + "<br>" +
                        "<em>some more message here.</em>";
                    Trace.Warn("ddlReason setting thankyou: " + lblThankYou.Text);
                    lblHiddenEmail.Text = ConfigurationManager.AppSettings["SD" + placething];

                    // Make phone number required
                    lblPhoneRequired.Visible = true;
                    cvPhone.Enabled = true;
                    break;

                default:
                    break;
            }// END switch

            // DEBUG to display where email is going to
            lblDEBUG.Text = lblHiddenEmail.Text;
        }

    }

    protected void ddlRegionalthing_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlRegionalthing.SelectedIndex > 0)
        {
            pnlddlreason.Visible = true;
            lblHdnthing.Text = ddlRegionalthing.SelectedValue.ToString();
            placething = lblHdnthing.Text;
            placething = ddlRegionalthing.SelectedValue.ToString();
            Trace.Warn("placething: " + placething);
        }
        else
        {
            HideAllForms();
            pnlddlreason.Visible = false;
            //lblHdnthing.Text = "";
            //placething = lblHdnthing.Text;
            placething = "";
        }
    }

    protected void HideAllForms()
    {
        pnlAccount.Visible = false;
        pnlCert.Visible = false;
        pnlComment.Visible = false;
        pnlInquiry.Visible = false;
        pnlSurvey.Visible = false;
        pnlEmail.Visible = false;
        pnlfilenamehere.Visible = false;
        pnlPersonal.Visible = false;
        pnlReferral.Visible = false;
        pnlRequest.Visible = false;
        pnlThank.Visible = false;
        pnlQuestion.Visible = false;
        pnlOther.Visible = false;
    }

    protected void cvPhone_ServerValidate(object source, ServerValidateEventArgs args)
    {
        Trace.Warn("Phone Validation");
        if (txtPartB.Text.Trim() == "" || txtPartC.Text.Trim() == "")
        {
            Trace.Warn("Phone not filled in");
            args.IsValid = false;
        }
        else
        {
            Trace.Warn("Phone number GOOD");
            args.IsValid = true;
        }
    }

    protected void ddlThisInquiry_DataBound(object sender, EventArgs e)
    {
        // ddlReason.selectedindex = 1;
        // ddlReason.Items[1].Selected = true;
        ddlReason.SelectedValue = "filenamehere";
    }


}


0
 
LVL 2

Assisted Solution

by:IndianHero2001
IndianHero2001 earned 500 total points
ID: 24393843
1. Check if you forgot declaring an item with ID="lblThankYou" in server control Syntax.

2. Also check the project path where you saved this User Control project or the one where you are getting that objectreference error. Remove # and & characters from Project Path if present.

0
 

Author Comment

by:celler_wellbridge
ID: 24433733
You were right about posting the entire code as the issue was not revealed in the snippet.

The issue has been resolved but not as expected.

Because the issue was not solved where the yellow error page pointed, it was discovered in another place entirely.

The DDL in the ascx file referenced a small array in the ascx.cs code behind file.

The array listed locations by their folder structure name.

Another department changed the folder structure name!

In the web.config the location was still listed using the original name (as it will not be updated automatically when something changes in the CMS!).

Changed the location name in the web.config to match the renamed folder structure in the CMS and now the page works.

Thank you for the effort and support.

Sometimes we need to look at other unrelated possibilities regardless of what the error page tells us.

...another leanring opportunity.
0
 

Author Closing Comment

by:celler_wellbridge
ID: 31656984
Thank you for the support! By indicating the issue was not in the code snippet provided, I looked around at other possibilities and stumbled upon the "real" issue!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Using SQL Scripts we can save all the SQL queries as files that we use very frequently on our database later point of time. This is one of the feature present under SQL Workshop in Oracle Application Express.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

705 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

19 Experts available now in Live!

Get 1:1 Help Now