Solved

Airline dbConnect.Close() unassigned.

Posted on 2012-04-06
12
419 Views
Last Modified: 2012-04-06
Error      1      Use of unassigned local variable 'dbConnection'      C:\Course Technology\CIS Programming\ASP .NET Programming\Data Files\Chapter.09\Chapter\SkywardAviation\Registration.aspx.cs      30      17      C:\...\SkywardAviation\

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 0)
            hiddenPassword.Value = password.Text;
    }
    protected void Page_LoadComplete(object sender, EventArgs e)
        {
             SqlConnection dbConnection;
if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 3)
        {
            dbConnection
                = new SqlConnection(
                    "Data Source=.\\SQLEXPRESS; AttachDbFilename=C:\\Course Technology\\CIS Programming\\ASP .NET Programming\\Data Files\\Chapter.09\\Chapter\\SkywardAviation.mdf; Integrated Security=True; User Instance=True");
            }
                             
            try
            {
                dbConnection.Open();
                SqlCommand sqlCommand = new SqlCommand(
                "INSERT INTO FrequentFlyers (last, first,"
                + " phone, email, password, cardType,"
                + " expireMonth, expireYear, cardnumber,"
                + " cardholder, address, city, state, zip,"
                + " travelerType, homeAirport, class, seat,"
                + " meal) VALUES("
                + "'" + lastName.Text + "',"
                + "'" + firstName.Text + "',"
                + "'" + telephone.Text + "',"
                + "'" + email.Text + "',"
                + "'" + hiddenPassword.Value + "',"
                + "'" + creditcard.Text + "',"
                + "'" + expireMonth.Text + "',"
                + "'" + expireYear.Text + "',"
                + "'" + cardnumber.Text + "',"
                + "'" + cardholder.Text + "',"
                + "'" + address.Text + "',"
                + "'" + city.Text + "',"
                + "'" + state.Text + "',"
                + "'" + zip.Text + "',"
                + "'" + travelerType.Text + "',"
                + "'" + homeAirport.Text + "',"
                + "'" + serviceClass.Text + "',"
                + "'" + seatPreference.Text + "',"
                + "'" + mealRequest.Text + "',)",
                dbConnection);
            sqlCommand.ExecuteNonQuery();
            sqlCommand = new SqlCommand(
                "SELECT IDENT_CURRENT('FrequentFlyers')",
                dbConnection);
            SqlDataReader lastID=
                sqlCommand.ExecuteReader();
            if (lastID.Read())
                successString.Text += "<h3>Enrollment Sucessful</h3>" +
                "<p>Your frequent flyer number is " +
                lastID.GetValue(0) + ".</p>";
        }
       catch (SqlException exception)
       {
            successString.Text += "<p>Error code "
                + exception.Number
                + ": " + exception.Message + "</p>";
}
dbConnection.Close();
       
}
}

this is homework.  I just have this error.  I do not understand why I am getting this error.  Thank you.  It says that the dbConnect.Open() is unassigned.  I really appreciate the patience of the experts.
homework-image.pdf
0
Comment
Question by:assaultkitty
[X]
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
  • 5
  • 5
  • 2
12 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37818078
This is because the only place you initialized your dbConnect variable is within the body of your if block. What happens if your if is never entered? You need to make sure all paths through your code prior to your usage of dbConnect either initialize this variable or return from the function (if appropriate).
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 37818079
For code part:

dbConnection
                = new SqlConnection(
                    "Data Source=.\\SQLEXPRESS; AttachDbFilename=C:\\Course Technology\\CIS Programming\\ASP .NET Programming\\Data Files\\Chapter.09\\Chapter\\SkywardAviation.mdf; Integrated Security=True; User Instance=True");

Open in new window


I would like to share something. Why don't you put the .mdf file in App_Data folder? As it is meant for such tasks. And then write connection string as:

string conString = @"Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\SkywardAviation.mdf; Integrated Security=True; User Instance=True";

Open in new window


Second if you have noticed we have added verbatim (@) before conString value otherwise compiler would throw error for newline constant in string for //.

So I assume that actually the error is newline constant (something like that) but compiler is pointing to other one. Try suggestions and let us know if problem still persists.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37818094
@vs00saini

EE wrapped her connection string when she pasted it into the text box during the creation of his question. If you copy/paste to a text editor, you will see that it is only one line  = )
0
Industry Leaders: 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!

 

Author Comment

by:assaultkitty
ID: 37818095
I am not getting a newline constant error. I am getting the following error:


Error      1      Use of unassigned local variable 'dbConnection'      C:\Course Technology\CIS Programming\ASP .NET Programming\Data Files\Chapter.09\Chapter\SkywardAviation\Registration.aspx.cs      30      17      C:\...\SkywardAviation\


Neither of the suggestion from the experts worked. Also, I looked on Google first before I asked. I could not find a proper solution.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37818099
Neither of the suggestion from the experts worked.
That's rather bold, since I didn't actually suggest code, but rather what you needed to do to correct the issue. Please show what you did to try to correct the issue. I assure you that your issue is as I mentioned.
0
 
LVL 16

Accepted Solution

by:
Vikram Singh Saini earned 500 total points
ID: 37818113
@kaufmed

Yes! You are right. Actually I thought that otherwise. And your first comment is true for solution. I'm just elaborating it codewise.


protected void Page_LoadComplete(object sender, EventArgs e)
        {
             SqlConnection dbConnection = new SqlConnection(
                    "Data Source=.\\SQLEXPRESS; AttachDbFilename=C:\\Course Technology\\CIS Programming\\ASP .NET Programming\\Data Files\\Chapter.09\\Chapter\\SkywardAviation.mdf; Integrated Security=True; User Instance=True");

if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 3)
        {
             // your code part here
            // we have initialized dbConnection out of if so that in any case it would be initialized
        }
0
 

Author Comment

by:assaultkitty
ID: 37818124
I am sorry Kaufmed. I tried your suggest, too.  I did put the connection string on one line.  The error did not resolve itself.  I apologize.  We are almost there.  I will cut and paste the suggestion so that you can see what I am talking about. I do know what a connection string is.  

Here is the code that I used for the suggestions.

First suggestion.  I pasted the connection string on one line.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 0)
            hiddenPassword.Value = password.Text;
    }
    protected void Page_LoadComplete(object sender, EventArgs e)
        {
             SqlConnection dbConnection;
if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 3)
        {
            dbConnection= new SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename=C:\\Course Technology\\CIS Programming\\ASP .NET Programming\\Data Files\\Chapter.09\\Chapter\\SkywardAviation.mdf; Integrated Security=True; User Instance=True");
            }
                             
            try
            {
                dbConnection.Open();
                SqlCommand sqlCommand = new SqlCommand(
                "INSERT INTO FrequentFlyers (last, first,"
                + " phone, email, password, cardType,"
                + " expireMonth, expireYear, cardnumber,"
                + " cardholder, address, city, state, zip,"
                + " travelerType, homeAirport, class, seat,"
                + " meal) VALUES("
                + "'" + lastName.Text + "',"
                + "'" + firstName.Text + "',"
                + "'" + telephone.Text + "',"
                + "'" + email.Text + "',"
                + "'" + hiddenPassword.Value + "',"
                + "'" + creditcard.Text + "',"
                + "'" + expireMonth.Text + "',"
                + "'" + expireYear.Text + "',"
                + "'" + cardnumber.Text + "',"
                + "'" + cardholder.Text + "',"
                + "'" + address.Text + "',"
                + "'" + city.Text + "',"
                + "'" + state.Text + "',"
                + "'" + zip.Text + "',"
                + "'" + travelerType.Text + "',"
                + "'" + homeAirport.Text + "',"
                + "'" + serviceClass.Text + "',"
                + "'" + seatPreference.Text + "',"
                + "'" + mealRequest.Text + "',)",
                dbConnection);
            sqlCommand.ExecuteNonQuery();
            sqlCommand = new SqlCommand(
                "SELECT IDENT_CURRENT('FrequentFlyers')",
                dbConnection);
            SqlDataReader lastID=
                sqlCommand.ExecuteReader();
            if (lastID.Read())
                successString.Text += "<h3>Enrollment Sucessful</h3>" +
                "<p>Your frequent flyer number is " +
                lastID.GetValue(0) + ".</p>";
        }
       catch (SqlException exception)
       {
            successString.Text += "<p>Error code "
                + exception.Number
                + ": " + exception.Message + "</p>";
}
    dbConnection.Close();
       
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 0)
            hiddenPassword.Value = password.Text;
    }
    protected void Page_LoadComplete(object sender, EventArgs e)
        {
             SqlConnection dbConnection;
if (Page.IsPostBack
            && enrollmentForm.ActiveViewIndex == 3)
        {
            string conString = @"Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\SkywardAviation.mdf; Integrated Security=True; User Instance=True";
        }
                             
            try
            {
                dbConnection.Open();
                SqlCommand sqlCommand = new SqlCommand(
                "INSERT INTO FrequentFlyers (last, first,"
                + " phone, email, password, cardType,"
                + " expireMonth, expireYear, cardnumber,"
                + " cardholder, address, city, state, zip,"
                + " travelerType, homeAirport, class, seat,"
                + " meal) VALUES("
                + "'" + lastName.Text + "',"
                + "'" + firstName.Text + "',"
                + "'" + telephone.Text + "',"
                + "'" + email.Text + "',"
                + "'" + hiddenPassword.Value + "',"
                + "'" + creditcard.Text + "',"
                + "'" + expireMonth.Text + "',"
                + "'" + expireYear.Text + "',"
                + "'" + cardnumber.Text + "',"
                + "'" + cardholder.Text + "',"
                + "'" + address.Text + "',"
                + "'" + city.Text + "',"
                + "'" + state.Text + "',"
                + "'" + zip.Text + "',"
                + "'" + travelerType.Text + "',"
                + "'" + homeAirport.Text + "',"
                + "'" + serviceClass.Text + "',"
                + "'" + seatPreference.Text + "',"
                + "'" + mealRequest.Text + "',)",
                dbConnection);
            sqlCommand.ExecuteNonQuery();
            sqlCommand = new SqlCommand(
                "SELECT IDENT_CURRENT('FrequentFlyers')",
                dbConnection);
            SqlDataReader lastID=
                sqlCommand.ExecuteReader();
            if (lastID.Read())
                successString.Text += "<h3>Enrollment Sucessful</h3>" +
                "<p>Your frequent flyer number is " +
                lastID.GetValue(0) + ".</p>";
        }
       catch (SqlException exception)
       {
            successString.Text += "<p>Error code "
                + exception.Number
                + ": " + exception.Message + "</p>";
}
    dbConnection.Close();
       
}
}
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37818144
Please reread my first comment, and be sure you understand what I indicating. As a simplified example, the following is what you have. For the sake of simplicity, when I say "initialization," think "new".

SqlConnection dbConnection;  // 1

if (true)   // 2
{
    dbConnection = new SqlConnection("some string");
}

dbConnection.Open();   // 3

Open in new window


In the above, these are the three things going on:

1.

A variable of type SqlConnection is being declared

2.

An if statement initializes the variable

3.

The instantiated variable has a method called against it
In the above, I have hard-coded the condition for the if to true, so it will always execute, and the variable will always be initialized. Since the variable is initialized, the call to the method in #3 will run just fine, because there is an object in memory to execute the method against. Now, what if I take that same code, and I change the hard-coded value for #2 in this way:

SqlConnection dbConnection;  // 1

if (false)   // 2
{
    dbConnection = new SqlConnection("some string");
}

dbConnection.Open();   // 3

Open in new window


Now the condition for the if can never be true (i.e. it's always false), which means the variable never gets initialized. This is a problem.

When a variable isn't properly initialized, it's value defaults to null.* It is very bad to have null variables, and the reason is that you cannot call a method against a null variable--there is nothing in memory to execute against. If we left the code with the hard-coded false for #2, then #3 will raise an exception because you are trying to execute a method against null. This both can never happen and does not make sense. You must be sure to initialize your variables--no matter what conditions your code may or may not check. There are a couple of ways you can solve your issue, but rather than just telling you an answer (which is rather taboo on EE since this is technically a homework question), I am trying to get you to think about why you are getting the behavior you are getting.

* This is only for reference types. I didn't want to get too deep into that with you though, so I generalized. Value types cannot be null.
0
 

Author Comment

by:assaultkitty
ID: 37818176
Here is the textbook I am using to do this program.  It is not the answer you are giving me.  I have to do 9.1 Project in the book for to turn in. I just want to make sure that it is working before I do the project.  I understand what you are say.  I just want you to look at the book to see what I have to do.
homework-image.pdf
Project.pdf
homework-1.pdf
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37818183
According to the instructions on page 473, I believe the authors intended for you to put the try/catch within the body of the if block (i.e. before the if's closing brace). You currently have your try/catch outside of the body of the if block. The wording of that part of the question is a bit confusing.
0
 

Author Comment

by:assaultkitty
ID: 37818219
I almost overlooked your message.  I found it and it is working.  The website came up.  You are an EXPERT.  I think your attentiveness and understanding.
0
 

Author Closing Comment

by:assaultkitty
ID: 37818221
This one did the trick.  I do not know what to add to the comments in this statement.  This author is a mess.
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

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.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

737 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