0

使用,

Visual Studio 2012 C# WPF SQL Server Compact 4.0

我有我的代码在这里。当我提交我的 categoryName 时,它​​显示

“ExecuteNonQuery:连接属性尚未初始化”

请帮助我。我正在尝试将数据从文本框添加到数据库。

    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();
    }
4

2 回答 2

3

您错过了将连接实例传递给SqlCeCommand

SqlCeCommand com = new SqlCeCommand("INSERT INTO Category_Master(CategoryName) VALUES(@CategoryName)",con);
于 2013-10-24T10:20:12.960 回答
0

分配连接属性

com.Connection = con
于 2013-10-24T10:38:39.467 回答