Click here to Skip to main content
15,881,715 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
current error: Object reference not set to an instance of an object
I was getting invalid cast exception error but i changed (int) to Convert.toInt32 and that went away.

I go to debug it and the on my button click and the code runs all the way through not stopping at any of my breakpoints. The object reference I pass in I get all the info no problem, pass in user and set it to currentUser to read the data of object. A record is inserted into my Customer Database BUT all of the info im passing IS NOT THERE so I know I am having some kind of problem with that which im still not sure of yet.

In the Combo box selection is when you go to "Yes" and click yes button with messagebox it inserts a New customer into the table.
On the edit profile / save profile button click i am just updating / adding the new data.

C#
//it would be in this section my error
private void BtnProfileEdit_Click(object sender, RoutedEventArgs e)
        {
            //User NewCustomer = null;
            //NewCustomer = UsersDB.GetUserById(currentCustomer.UserID);
            //Customer NewCustomer = null;
            //NewCustomer =(Customer) UsersDB.GetUserById(currentCustomer.UserID);
            //NewCustomer = (Customer)currentCustomer;
            //(User) NewCustomer = currentCustomer;
            //currentCustomer = (User)NewCustomer;
            //currentCustomer = NewCustomer;
            //Change button content to 'Save'.
            
            EnableControls();
            //MessageBox.Show(currentCustomer.GetType() + " VS " + NewCustomer.GetType());

            if (boolBtnPush == true)
            {
                if (BtnProfileEdit.Content.Equals("Save"))
                //if(BtnProfileEdit.Content.ToString() == "Save")
                //error label.
                {
                    if(boolIsCustomer == true)
                    //if (currentUser.IsCustomer == true)
                    //if (NewCustomer.FirstName.Equals(""))
                    {
                        if (TextboxFirstName.Text.Equals(""))
                        {   //Display messagebox so user MUST enter firstname.
                            MessageBox.Show("You 'MUST' enter a First name,", "WARNING", MessageBoxButton.OK);
                        }
                        else
                        {
                            try
                            {
                                //customerLoaded
                                testcus = new Customer(currentUser.UserID, TextboxFirstName.Text,
                                    TextboxLastName.Text, TextboxAddress.Text, TextboxCity.Text,
                                    ComboboxState.SelectedValue.ToString(), TextboxZip.Text, TextEmailAddress.Text);
                                UsersDB.UpdateCustomer(testcus);

                                //Window SrcCustomerScreen = new CustomerScreen(currentUser);
                                ////or use newcustomer to insert values.
                                //SrcCustomerScreen.Show();
                                //Close();
                            }
                            catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
                        }
                    }
                    else
                    {
                        MessageBox.Show("You must select 'Yes' in combobox Customer\n" +
                            "to add customer data.", "UnAcceptable", MessageBoxButton.OK);
                    }                  
                }
            }
            //ON THE FIRST BUTTON CLICK DO THIS SO ON SECOND ABOVE CODE IS EXECUTED.
            boolBtnPush = true;
            BtnProfileEdit.Content = "Save";
        }

        private void Btntest_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(currentUser.ToString());
        }

        private void CboCustomer_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string cboValue = "";
            if (CboCustomer.SelectedIndex > 0)
                cboValue = ((ComboBoxItem)CboCustomer.SelectedItem).Content.ToString();
                //(ComboBoxItem)CboCustomer.SelectedItem)
            if(cboValue.Equals("Yes"))
            //if (CboCustomer.SelectedItem..ToString().Equals("Yes"))
            {
                boolIsCustomer = true;
                User addCustomer = null;
                Customer newCustomer = null;

                MessageBoxResult result = MessageBox.Show("Updating database to customer status.",
                    "Customer Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
                if (result == MessageBoxResult.Yes)
                {
                    try
                    {
                        addCustomer = new User(currentUser.UserID, currentUser.Username,
                            currentUser.Password, currentUser.IsAdmin, currentUser.UserCreatedDate, boolIsCustomer);
                        UsersDB.UpdateCurrentUser(addCustomer);
                        //Create New Customer
                        newCustomer = new Customer(currentUser.UserID, currentUser.Username, null, null,
                                                    null, null, null, null);
                        UsersDB.CreateCustomer(newCustomer);

                        //Load the newly created customer object so it can be read.
                        //customerLoaded = UsersDB.ReadCustomerById(currentUser.UserID);
                        //PopulateControls(customerLoaded);
                    }
                    catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
                }
                //else
                   // boolIsCustomer = false;
            }        }
    }
//AND HERE IS WHERE MY METHODS CREATE CUSTOMER AND UPDATE CUSTOMER THAT I USE.
public static int CreateCustomer(Customer customer)
        {
            string SQLcreateQuery = "INSERT INTO Customers (UserId, FirstName, LastName, Address, " +
                "City, State, ZipCode, EmailAddress) VALUES(@id, @fn, @ln, @ad, @ci, @st, @zc, @ea)";
            SqlCommand cmdCreate = new SqlCommand(SQLcreateQuery, connection);
            cmdCreate.Parameters.AddWithValue("@id", customer.UserID);
            cmdCreate.Parameters.AddWithValue("@fn", customer.FirstName ?? Convert.DBNull);
            cmdCreate.Parameters.AddWithValue("@ln", customer.LastName ?? Convert.DBNull);
            cmdCreate.Parameters.AddWithValue("@ad", customer.Address ?? Convert.DBNull);
            cmdCreate.Parameters.AddWithValue("@ci", customer.City ?? Convert.DBNull);
            cmdCreate.Parameters.AddWithValue("@st", customer.State ?? Convert.DBNull);
            cmdCreate.Parameters.AddWithValue("@zc", customer.ZipCode ?? Convert.DBNull);
            cmdCreate.Parameters.AddWithValue("@ea", customer.EmailAddress ?? Convert.DBNull);
            try
            {
                connection.Open();
                cmdCreate.ExecuteNonQuery();
                string SQLselect = "SELECT @@IDENTITY FROM Customers";
                SqlCommand cmdSELECT = new SqlCommand(SQLselect, connection);
                int CustomerId = Convert.ToInt32(cmdSELECT.ExecuteScalar());
                return CustomerId;
            }
            catch (Exception ex) { throw ex; }
            finally { connection.Close(); }
        }
        //READ
        public static Customer ReadCustomerById(int id)
        {
            string SQLreadQuery = "SELECT * FROM Customers WHERE UserId=@uid";
            SqlCommand cmdRead = new SqlCommand(SQLreadQuery, connection);
            cmdRead.Parameters.AddWithValue("@uid", id);
            try
            {
                connection.Open();
                SqlDataReader reader = cmdRead.ExecuteReader(CommandBehavior.SingleRow);
                if (reader.Read())
                {
                    Customer customer = new Customer()
                    {
                        UserId = Convert.ToInt32(reader["UserId"]),
                        /*Username = reader["Username"].ToString(),
                        Password = reader["Password"].ToString(),
                        IsAdmin = Convert.ToBoolean(reader["IsAdmin"]),
                        UserCreatedDate = Convert.ToDateTime(reader["UserCreatedDate"]),*/
                        FirstName = reader["FirstName"].ToString(),
                        LastName = reader["LastName"].ToString(),
                        Address = reader["Address"].ToString(),
                        City = reader["City"].ToString(),
                        State = reader["State"].ToString(),
                        ZipCode = reader["ZipCode"].ToString(),
                        EmailAddress = reader["EmailAddress"].ToString()
                    };
                    return customer;
                }
                else
                    return null;
            }
            catch(Exception ex) { throw ex; }
            finally { connection.Close(); }
        }
        //UPDATE
        public static bool UpdateCustomer(Customer customer)
        {
            bool result = false;
            string SQLupdateQuery = "UPDATE Customers SET FirstName=@fn, LastName=@ln, " +
                "Address=@ad, City=@ci, State=@st, ZipCode=@zc, EmailAddress=@ea " +
                "WHERE UserId=@cid";
            SqlCommand cmdUpdate = new SqlCommand(SQLupdateQuery, connection);
            cmdUpdate.Parameters.AddWithValue("@cid", customer.UserId);
            cmdUpdate.Parameters.AddWithValue("@fn", customer.FirstName);
            cmdUpdate.Parameters.AddWithValue("@ln", customer.LastName);
            cmdUpdate.Parameters.AddWithValue("@ad", customer.Address);
            cmdUpdate.Parameters.AddWithValue("@ci", customer.City);
            cmdUpdate.Parameters.AddWithValue("@st", customer.State);
            cmdUpdate.Parameters.AddWithValue("@zc", customer.ZipCode);
            cmdUpdate.Parameters.AddWithValue("@ea", customer.EmailAddress);
            try
            {
                connection.Open();
                cmdUpdate.ExecuteNonQuery();
                result = true;
            }
            catch(Exception ex)
            {
                ex.Message.ToString();
                throw ex;
            }            
            finally { connection.Close(); }
            return result;
        }


What I have tried:

debugging but the button click runs through and no breakpoints hit
Posted
Updated 9-Nov-18 19:59pm

1 solution

The debugger is pretty much the only way you will find this: if you aren't hitting the breakpoints, then either they aren't in the right place, or you are not debugging the code you are executing.

So: try it again. Go to the "Debug" menu and select the "Exceptions..." menu item.
In the resulting dialog, make sure there is a tick in all boxes: "Thrown" and "User-unhandled" then press OK.

Run your app in the debugger, and when an exception is thrown it will break - even if it is inside a try ... catch block.
Now look and see why.

Sorry, but we can:t do that for you!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900