对象引用,c#

时间:2015-10-27 08:08:50

标签: c# mysql

using MySql.Data.MySqlClient;

namespace SSK_projekt
{
    public partial class removeuserform : Form
    {
        //Connection variables.
        private string conn;
        private MySqlConnection connect;
        public removeuserform()
        {
            InitializeComponent();
        }

        private void db_connection()
        {
            try
            {
                conn = "Server=localhost;Database=ssk;Uid=root;Pwd=password;";
                connect = new MySqlConnection(conn);
                connect.Open();
            }
            catch (MySqlException)
            {
                throw;
            }
        }

        private void removeuserform_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string ett = textBox1.Text;
            if (ett == "")
            {
                MessageBox.Show("Du måste fylla i UID, vilket du finner i användarlistan.");
                return;
            }
            try
            {
                if (connect.State == ConnectionState.Open)
                {
                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = connect;
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@uid", textBox1.Text);
                    cmd.CommandText = "DELETE FROM Users WHERE uid = @uid";
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Användaren borttagen.");
                }
                else
                {
                    MessageBox.Show("Något gick tyvärr fel, kontakta systemadministratören.");
                }
            }
            catch (Exception ex)
            {
                { MessageBox.Show(ex.Message); }
            }
        }
    }
}

我收到以下错误:

Error:object reference not set to an instance of an object.

我以前从来没有偶然发现过这个问题。 SQL语法是正确的,我在sql debugger&它工作得很好。 变量被声明,因此它不能是......

1 个答案:

答案 0 :(得分:0)

您必须先致电if (connect.State == ConnectionState.Open)才能使用

connect

否则State为空且没有ul { width: 300px; }属性