所以我寫了我的代碼,但每次我嘗試執行它說「異常未處理System.InvalidOperationException:'填充:SelectCommand.Connection屬性尚未初始化。」,它始終顯示它在說da .fill僞(DT);如何解決我的代碼時說異常未處理?
請告訴我如何解決它
namespace FairyTailHRSolution
{
public partial class Form1 : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
con=new SqlConnection(@"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True");
con.Open();
cmd = new SqlCommand("INSERT INTO FRYEMP (EmployeeID, EmployeeName, EmployeePosition, EmployeeSalary) VALUES (@EmployeeID, @EmployeeName, @EmployeePosition, @EmployeeSalary)", con);
cmd.Parameters.Add("@EmployeeID", textBox1.Text);
cmd.Parameters.Add("@EmployeeName", textBox2.Text);
cmd.Parameters.Add("@EmployeePosition", textBox3.Text);
cmd.Parameters.Add("@EmployeeSalary", textBox4.Text);
cmd.ExecuteNonQuery();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void find_Click(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(comboBox1.Text == "EmployeeID")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like @employeeID", con);
da.SelectCommand.Parameters.AddWithValue("@employeeID", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
else if (comboBox1.Text == "EmployeeName")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like @employeeName", con);
da.SelectCommand.Parameters.AddWithValue("@employeeName", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
你看了錯誤消息,想想它告訴你是錯的?你是否使用調試器來發現'con'在拋出異常的情況下明顯爲空? –
也許你應該嘗試初始化SelectCommand的Connection屬性。你已經爲SqlCommand正確地做了它。 –