对象引用,C# [英] Object reference, c#

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

问题描述

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 & 中运行了它.它工作得很好.变量已声明,因此也不可能是...

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

推荐答案

你必须调用 db_connection() 才能使用

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

if (connect.State == ConnectionState.Open)

否则 connect 为空且没有 State 属性

otherwise connect is null and has no State property

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

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