C#WPF对象引用未设置为对象的实例 [英] C# WPF object reference not set to an instance of an object

查看:65
本文介绍了C#WPF对象引用未设置为对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前错误:对象引用未设置为对象的实例

我收到了无效的强制转换异常错误,但我将(int)更改为Convert.toInt32并且消失了。



我去调试它,点击我的按钮,代码一直运行,不停在任何断点处。我传入的对象引用我得到的所有信息都没问题,传入用户并将其设置为currentUser来读取对象的数据。一条记录被插入到我的客户数据库中,但是所有的信息都没有通过,所以我知道我遇到了一些我还不确定的问题。



在组合框中选择是当你转到是并点击带有消息框的是按钮时,它会在表格中插入一个新客户。

在编辑个人资料/保存个人资料按钮上单击我我只是更新/添加新数据。



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.

//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

推荐答案

调试器几乎是你找到它的唯一方法:如果你不是没有碰到断点,要么他们不在正确的位置,要么你没有调试你正在执行的代码。



所以:再试一次。转到调试菜单并选择例外...菜单项。

在结果对话框中,确保所有框中都有勾号:投掷和用户未处理 然后按OK。



在调试器中运行你的应用程序,当抛出异常时它会中断 - 即使它在里面尝试...抓住阻止。

现在看看为什么。



抱歉,我们可以:为你做到这一点!
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!


这篇关于C#WPF对象引用未设置为对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆