Solved

VS C# Connection Property Not Been Initialized

Posted on 2012-12-27
9
409 Views
Last Modified: 2013-01-06
I have upgraded a program from VS C# 2008 to VS C# 2010. It is now set for .Net FW 3.5 where before it was .Net 2.0

When I run the code and this routine is called, I am now getting the message "Connection Property Has Not Been Initialized" on the cmd.ExecuteNonQuery() line. I tried inserting cmd.Connection.Open() before the execute but then I get "Object has not been set to an instance of an object" message. It appears something is different. How do I structure this code so the sp will fire?

private void InsertReasonForChange()
        {
            try
            {
                SqlCommand cmd = new SqlCommand();

                /* Insert/Update the reason for the sell price change */
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new SqlParameter("@SOPNUMBE", SOPNUMBE));
                cmd.Parameters.Add(new SqlParameter("@SOPTYPE", SOPTYPE));
                cmd.Parameters.Add(new SqlParameter("@LNITMSEQ", LNITMSEQ));
                cmd.Parameters.Add(new SqlParameter("@CMPSEQNM", CMPSEQNM));
                cmd.Parameters.Add(new SqlParameter("@USERID", GP_User_ID));
                cmd.Parameters.Add(new SqlParameter("@REASON", txtReason.Text));

                cmd.CommandText = "rbs_ChangeSellPriceReason";

                cmd.Connection = DataConnection;
               
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                string eMsg = "003: ERROR: " + ex.Message;
                if (stackTraceWanted) eMsg += "\n" + ex.StackTrace;
                if (stackTraceWanted) MessageBox.Show(eMsg);
            }
        }
0
Comment
Question by:rwheeler23
  • 4
  • 3
  • 2
9 Comments
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 38725749
Where is DataConnection initialized? You should have a line similar to:

SqlConnection DataConnection = new SqlConnection("your connection string here");

Open in new window

0
 
LVL 9

Expert Comment

by:gt2847c
ID: 38725754
You need an open SqlConnection in order to do what you're attempting...  You appear to be assigning the connection:

cmd.Connection = DataConnection;

however I don't see where DataConnection is coming from in your code snippet above.

DataConnection would have to be a SqlConnection() created somewhere.  It would also need to be opened before you execute:

cmd.ExecuteNonQuery();

Typically you will want to open the connection, execute, then close.  Often this is done inside a using statement so that you don't leave resources hanging around.

Microsoft's example code looks like this:

private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandTimeout = 15;
        command.CommandType = CommandType.Text;
        command.CommandText = queryString;

        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}",
                reader[0], reader[1]));
        }
    }
}

Open in new window

0
 
LVL 9

Expert Comment

by:gt2847c
ID: 38725760
If, by chance, DataConnection is a property set on your object class containing InsertReasonForChange, you may need to put some code in to verify that DataConnection was properly set up before you try and use it in your function.  It may be that your code is failing due to your function assuming that DataConnection initialization was handled before InsertReasonForChange is called and that not being the case.  Placing some error checking code in to validate that DataConnection is properly initialized may help you correct this problem and prevent others.

This could be in the form of a private internal flag set when DataConnection is initialized or some equivalent sort of mechanism.
0
 

Author Comment

by:rwheeler23
ID: 38725806
I have attached the entire section of this code. We have a connect reference call GPConnet that actually makes the connection. I have used this for years just as in this code but now that I have upgraded it no longer appears to work as originaly designed. There never was a line that actually opens the connection. I know it is open because I get an error message if I try to open it while it is open. I get the message "Object has not been set to an instance of an object" . If you could provide some guidance as to how to validate the connection. All I have ever done before is create the connection, do whatever I need to do and then close the connection upon termination.

All this code is doing is popping up a box teling the user the change something and asks for a reason for the change. I need this reason written back to a table in the database. InsertReasonForChange is called when the Save button is clicked.
CodeSnippet.txt
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:rwheeler23
ID: 38725819
P.S. I put in some breakpoints and I can see the GP _User_ID has the correct value however, the value of DataConnection is null. So I do not see the variables returne dfrom GPConnect have values but the connection is null.
0
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 250 total points
ID: 38725838
Change line 28 of the file you posted from:

SqlConnection DataConnection = GetConnection();

to...

this.DataConnection = GetConnection();

Open in new window


Then uncomment line 104.
0
 
LVL 9

Accepted Solution

by:
gt2847c earned 250 total points
ID: 38725839
Looking at your code I see several items that don't make much sense to me...

You create a private variable DataConnection at the top of your class declaration:

private System.Data.SqlClient.SqlConnection DataConnection;

In most of your functions, you declare another DataConnection local to that function:

Your constructor has one:
try
            {
                SqlConnection DataConnection = GetConnection();
            }

GetConnection has one:
SqlConnection DataConnection = new SqlConnection();

Both of those declarations will hide the one at the class level.

Your InsertReasonForChange() function references the private DataConnection at the class level which has never been set.  If this code worked for you before, I am not sure how...

A one line fix would be to change your constructor from:

public frmSOPCheckSellPrice(string ordnmbr, Int16 ordtype, int linenmbr, int compnmbr)
        {
            InitializeComponent();

            try
            {
                SqlConnection DataConnection = GetConnection();
            }
            catch (Exception ex)

Open in new window


to:

public frmSOPCheckSellPrice(string ordnmbr, Int16 ordtype, int linenmbr, int compnmbr)
        {
            InitializeComponent();

            try
            {
                // SqlConnection DataConnection = GetConnection();
                DataConnection = GetConnection();
            }
            catch (Exception ex)

Open in new window


That would set the class level DataConnection so it would not be null.  Normally, I'd say you also need a DataConnection.Open(), but I've not worked with Dynamics before, so the
connection you create in GetConnection using the GPConnObj.Connect() may take care of that for you.
0
 
LVL 9

Expert Comment

by:gt2847c
ID: 38725848
Another thing to think about is variable naming.  Current convention has private class variables named with a leading underscore to help you differentiate what your setting.

Private class variables
private object _myObject;

Private/Public/Protected Parameter:
public object MyObject { get;set; }

Variables local to function:
object myObject;

The capitalization and the leading underscore can make it a lot easier to figure out what it is you are setting and makes code easier to read.
0
 

Author Comment

by:rwheeler23
ID: 38725864
Damn, you guys are good! This is a great teachable moment and I am learning from the best. I make these minor changes and there goes my sp. Thank you so very much!
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
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…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

706 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

18 Experts available now in Live!

Get 1:1 Help Now