2013-10-24 163 views
0

使用,ExecuteNonQuery:連接屬性尚未初始化。我堅持

的Visual Studio 2012 C# WPF 的SQL Server Compact 4.0

我有我的代碼在這裏。當我提出我的類別名稱就說明

「的ExecuteNonQuery:Connection屬性尚未初始化」

plz幫助我。我正在嘗試將數據從文本框添加到數據庫。

private void btnCategoryAdd_Click(object sender, RoutedEventArgs e) 
    { 
     con.Open(); 
     SqlCeCommand com = new SqlCeCommand("INSERT INTO Category_Master(CategoryName) VALUES(@CategoryName)"); 
     com.Parameters.AddWithValue("@CategoryName", tbCategoryName.Text); 

     try 
     { 
      int affectedRows = com.ExecuteNonQuery(); 
      if (affectedRows > 0) 
      { 
       System.Windows.Forms.MessageBox.Show("Insert Success !", System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); 
       tbCategoryName.Text = ""; 
      } 
      else 
      { 
       System.Windows.Forms.MessageBox.Show("Insert Failed !", System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
      } 
     } 
     catch (Exception ex) 
     { 
      System.Windows.Forms.MessageBox.Show(ex.Message, System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
     con.Close(); 
    } 

回答

3

你錯過了連接實例傳遞給SqlCeCommand

SqlCeCommand com = new SqlCeCommand("INSERT INTO Category_Master(CategoryName) VALUES(@CategoryName)",con); 
+0

嗨。謝謝。我認爲它的工作。但出現另一個錯誤。列不能包含空值。是因爲我的數據庫是空的。如何克服這一點。我也有一個名爲categoryID的列。這不是沒有,主要的和獨特的。 – Kamal

+0

Ys。有效。我忘了爲唯一ID添加自動增量。 – Kamal

+0

@KaMaLMoHaN很高興它幫助你.. –

0

指定連接屬性

com.Connection = con 
相關問題