Метода executereader: свойство Connection не инициализировано в C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace Database_ex1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } String cnStr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MyDB.mdf;Integrated Security=True;Connect Timeout=30"; private void Form1_Load(object sender, EventArgs e) { SqlConnection cn = new SqlConnection(cnStr); SqlDataAdapter da = new SqlDataAdapter("SELECT * From Employee", cn); DataSet ds = new DataSet(); da.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; } private void BtnAdd_Click(object sender, EventArgs e) { try { SqlConnection cn = new SqlConnection(cnStr); cn.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "INSERT INTO Employee(Employee id,Name,Sex,Salary)VALUES(N'" + TxtId.Text.Replace("'", "''") + "',N'" + TxtName.Text.Replace("'", "''") + "',N'" + CboSex.Text + "'," + TxtSalary.Text + ")"; cmd.Connection = cn; cmd.ExecuteNonQuery(); Form1_Load(sender, e); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void BtnUpdate_Click(object sender, EventArgs e) { try { SqlConnection cn = new SqlConnection(cnStr); cn.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "UPDATE Employee SET Name=N'" + TxtName.Text.Replace("'", "''") + "', Sex=N'" + CboSex.Text + "', Salary=" + TxtSalary.Text + " WHERE Employee id=N'" + TxtId.Text.Replace("'", "''") + "'"; cmd.Connection = cn; cmd.ExecuteNonQuery(); Form1_Load(sender, e); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void BtnDel_Click(object sender, EventArgs e) { try { SqlConnection cn = new SqlConnection(cnStr); cn.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "DELETE FROM Employee WHERE Employee id=N'" + TxtId.Text.Replace("'", "''") + "'"; cmd.Connection = cn; cmd.ExecuteNonQuery(); Form1_Load(sender, e); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void BtnSelect_Click(object sender, EventArgs e) { string sql = "SELECT * From Employee where Employee id = @Employee id"; try { using (SqlConnection cn = new SqlConnection(cnStr)) cn.Open(); { using (SqlCommand cmd = new SqlCommand(sql,cn)) { cmd.Parameters.AddWithValue("@Employee", TxtId.Text); cmd.ExecuteReader(); Form1_Load(sender, e); } } } catch (Exception ex) { MessageBox.Show(ex.Message); }
Что я уже пробовал:
Hi, so this error popped-up after I compiled my sql database code when I trying to use a button_click event to search for employee data (I'm using C# windows form application) I've been sitting here for 2 hours without a solution,and I don't know what's wrong with it. Thanks in advance!