Kamal
Kamal

Reputation: 477

ExecuteNonQuery: Connection property has not been initialized. I am stuck

Using,

Visual Studio 2012 C# WPF SQL Server Compact 4.0

I have my code here. When i submit my categoryName it shows

"ExecuteNonQuery: Connection property has not been initialized"

Plz help me. I am trying to add a data from textbox to database.

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

Upvotes: 0

Views: 349

Answers (2)

evhen14
evhen14

Reputation: 1927

Assign Connection Property

com.Connection = con

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73482

You missed to pass connection instance to SqlCeCommand

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

Upvotes: 3

Related Questions