对象引用,c#
本文关键字:对象引用 | 更新日期: 2023-09-27 18:19:19
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调试器&效果很好。变量是声明的,所以不能是…
你必须先调用db_connection()
才能使用
if (connect.State == ConnectionState.Open)
否则connect
为空且没有State
属性