-3
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); }
            }
        }
    }
}

I got the following error:

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

I've never stumbled on this issue before. The SQL syntax is correct and i've run it in sql debugger & it worked great. The variables are declared so it can't be that either...

user1
  • 3,763
  • 7
  • 29
  • 60
Hajpz
  • 41
  • 8

1 Answers1

0

you have to call db_connection() before your are able to use

if (connect.State == ConnectionState.Open)

otherwise connect is null and has no State property

fubo
  • 39,783
  • 16
  • 92
  • 127