• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 427
  • Last Modified:

Airline dbConnect.Close() unassigned.

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
assaultkitty
Asked:
assaultkitty
  • 5
  • 5
  • 2
1 Solution
 
käµfm³d 👽Commented:
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
 
Vikram Singh SainiSoftware Engineer cum AD DeveloperCommented:
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
 
käµfm³d 👽Commented:
@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
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.

 
assaultkittyAuthor Commented:
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
 
käµfm³d 👽Commented:
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
 
Vikram Singh SainiSoftware Engineer cum AD DeveloperCommented:
@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
 
assaultkittyAuthor Commented:
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
 
käµfm³d 👽Commented:
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
 
assaultkittyAuthor Commented:
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
 
käµfm³d 👽Commented:
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
 
assaultkittyAuthor Commented:
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
 
assaultkittyAuthor Commented:
This one did the trick.  I do not know what to add to the comments in this statement.  This author is a mess.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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.

  • 5
  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now