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

c# System.NullReferenceException: Object reference not set to an instance of an object

Posted on 2014-02-27
4
3,239 Views
Last Modified: 2014-02-28
Hello,
Please, help me to find out what is wrong. The code is below.
This is asp code:
<asp:Literal ID="LtError" runat="server" />
<asp:PlaceHolder ID="PhWrapper" runat="server">
<h2>Create New Ballot</h2>
<asp:MultiView ID="MvNewBallot" runat="server" ActiveViewIndex="0">
    <asp:View ID="ViewForm" runat="server">
        <div class="generic-form-section" style="text-align:center";>
                      
              <strong>Candidats:</strong><br />
               <p><strong>1.</strong><asp:TextBox ID="Cand1" Width="313px" runat="server" /><br />
              Information Link:<asp:TextBox ID="TxtLink1" Width="313px" runat="server" /><br /></p>
             <p>2.</strong><asp:TextBox ID="Cand2" Width="313px" runat="server" /><br />
            Information Link:<asp:TextBox ID="TxtLink2"  Width="313px" runat="server" /><br /></p>
       
             <p><strong>Status: </strong><asp:DropDownList ID="DdlStatus" runat="server">
                    <asp:ListItem Text="Active" Value="Active" />
                    <asp:ListItem Text="Inactive" Value="Inactive" Selected="True" />
              </asp:DropDownList></p>
        </div>   
        <p>
            <asp:LinkButton ID="BtnCreate" runat="server" Text="Create Ballot" CssClass="btn" OnClick="BtnCreate_Click" />
        </p>
    </asp:View>
    <asp:View ID="ViewThanks" runat="server">
        <p>The Ballot has been successfully created!</p>
    </asp:View>
</asp:MultiView>
</asp:PlaceHolder>

Open in new window

And in C#:
protected void BtnCreate_Click(object sender, EventArgs e)
        {
            try
            {
               
               AddNewResponses();
               MvNewBallot.SetActiveView(ViewThanks);
            }
            catch (Exception ex)
            {
                Response.Write(ex);

                LtError.Text = "An error has occurred while attempting to submit your application. <span style=\"display: none;\">" + ex.ToString() + "</span>";
            }
        }
        private void AddNewResponses()
        {
            CDataAccess da = null;
            using (da = new CDataAccess(_connectionString))
            {
                da.OpenConnection();
                int resseq = 0;

                foreach (Control ct in this.Controls)
                {
                    TextBox tb = ct as TextBox;
                    if (tb.ID.Contains("Cand"))
                    {
                        string rlink = "";
                        if (!string.IsNullOrWhiteSpace(tb.Text))   // (tb.Text.Length > 0) //&
                        {
                                ++resseq;
                                da.SelectParameterizedStoredProcedure("AddNewResponse");
                                da.AddInputObject("ResSeq", System.Data.SqlDbType.Int, resseq);
                                da.AddInputObject("ResText", System.Data.SqlDbType.VarChar, tb.Text);
                                if (tb.ID == "Cand1")
                                {
                                    rlink = TxtLink1.Text;
                                }
                                if (tb.ID == "Cand2")
                                {
                                    rlink = TxtLink2.Text;
                                }
                                
                                if (!String.IsNullOrWhiteSpace(rlink))
                                {
                                    da.AddInputObject("ResLink", System.Data.SqlDbType.VarChar, rlink);
                                }
                                da.ExecuteParameterizedCommand();
                                da.ClearResultsAndParameters();
                                da.CloseConnection();
                                da.Dispose();
                            }
                        }
                    }
                }
            }

Open in new window


Everytime i click on Create button i get error:
"System.NullReferenceException: Object reference not set to an instance of an object. at AddNewResponses() "
Any ideas?
Thank you.
0
Comment
Question by:kqureshi321
4 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39893875
This line:

TextBox tb = ct as TextBox;

Open in new window


...can result in null if the thing you are attempting to cast is not actually a TextBox. Are you certain that all of the controls you are looping over are actually TextBoxes?
0
 
LVL 12

Accepted Solution

by:
jitendra patil earned 500 total points
ID: 39894326
you need to keep a check for textbox control if you are only concerned about textbox as

you can also do this by the trick given below link using linq.
Finding all controls of a specific type on a page
the above method will save your time and looping part both.

you just need to get all textboxes from the above generic method and do the further processing, by using this you will be sure to get the  controls of type you need.

Hope this helps.
0
 

Author Closing Comment

by:kqureshi321
ID: 39894869
Works like a charm!
Thank you for pointing me in right direction! You saved me a lot of time.
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.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
C# LINQ ForEach() question 6 54
Release Dynamically Allocated Memory in C# 3 38
Iteration Help (Asp.net VB) 5 24
Input parameteres to DragOver 2 20
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

860 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