locked
ExecuteNonQuery: Connection property has not been initialized. RRS feed

  • Question

  • Hello,

    I have a problem when I run my Visual Studio Aplications. It shows this error: ExecuteNonQuery: Connection property has not been initialized.

    The code is:

    "

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;

    namespace ConsoleApplication1
    {
        public partial class Form2 : Form
        {
            SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Ramona\Desktop\ConsoleApplication1\ConsoleApplication1\Gestiune carti.mdf;Integrated Security=True;User Instance=True");
            SqlCommand comand=new SqlCommand();
         
            public Form2()
            {
                InitializeComponent();
            }

            private void label1_Click(object sender, EventArgs e)
            {
                //comand.Connection = cn;
            }

            private void btn_renunta_Click(object sender, EventArgs e)
            {
                Form2 frm = new Form2();
                frm.Show();
            }

            private void btn_adauga_Click(object sender, EventArgs e)
            {
                if (txt_id.Text !="" && txt_nume.Text != " " && txt_autor.Text!= " ")
                {

                   
                    cn.Open();
                    comand.CommandText=" Insert into Gestiune carti (ID_Carte,Nume, Autor) values("+txt_id.Text+","+txt_nume.Text+","+txt_autor.Text+")";
                    comand.ExecuteNonQuery();-here is the problem
                    MessageBox.Show("Carte adaugata");
                    cn.Close();
                }

            }
        }
    }
    "

    Monday, August 27, 2012 5:39 PM

Answers

  • ExecuteNonQuery() require a open a connection to execute the query. In your code Connection is opened but there is no assignment/ linking of an opened connection with your command instance.

    I can see some where it is been commented as below and this is not the righ tplace too.

    private void label1_Click(object sender, EventArgs e)
    {
     //comand.Connection = cn;
    }

    A solution to your issue is

    Option-One:  Allocate a connection instance to command object before you call ExecuteNonQuery i.e.

    comand.Connection = cn;
    comand.ExecuteNonQuery();

    Option- Two: Assign a connection at the time of creating instance of the SqlCommand(). i.e.

    SqlCommand comand=new SqlCommand("",cn);


    Lingaraj Mishra

    • Proposed as answer by Bob Wu-MT Wednesday, August 29, 2012 2:25 AM
    • Marked as answer by Bob Wu-MT Monday, September 3, 2012 5:45 AM
    Tuesday, August 28, 2012 11:35 AM