ExecuteNonQuery: Connection property has not been initialized

Posted by 20151012 on Stack Overflow See other posts from Stack Overflow or by 20151012
Published on 2012-12-14T05:02:12Z Indexed on 2012/12/14 5:03 UTC
Read the original article Hit count: 185

I get an error in my code:

The error point at dbcom.ExecuteNonQuery();.

Code(connection)

public admin_addemp()
    {
        InitializeComponent();
        con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\EMPS.accdb;Persist Security Info=True");
        con.Open();
        ds.Tables.Add(dt);
        ds.Tables.Add(dt2);
    }

Code (Save button)

private void save_btn_Click(object sender, EventArgs e)
    {
        OleDbCommand check = new OleDbCommand();
        check.Connection = con;
        check.CommandText = "SELECT COUNT(*) FROM employeeDB WHERE ([EmployeeName]=?)";
        check.Parameters.AddWithValue("@EmployeeName", tb_name.Text);
        if (Convert.ToInt32(check.ExecuteScalar()) == 0)
        {
            dbcom2 = new OleDbCommand("SELECT EmployeeID FROM employeeDB WHERE EmployeeID='" + tb_id.Text + "'", con);
            OleDbParameter param = new OleDbParameter();
            param.ParameterName = tb_id.Text;
            dbcom.Parameters.Add(param);
            OleDbDataReader read = dbcom2.ExecuteReader();

            if (read.HasRows)
            {
                MessageBox.Show("The Employee ID '" + tb_id.Text + "' already exist. Please choose another Employee ID.");
                read.Dispose();
                read.Close();
            }
            else
            {
                string q = "INSERT INTO employeeDB (EmployeeID, EmployeeName, IC, Address, State, " +
                    " Postcode, DateHired, Phone, ManagerName) VALUES ('" + tb_id.Text + "', " +
                    " '" + tb_name.Text + "', '" + tb_ic.Text + "', '" + tb_add1.Text + "', '" + cb_state.Text + "', " +
                    " '" + tb_postcode.Text + "', '" + dateTimePicker1.Value + "', '" + tb_hp.Text + "', '" + cb_manager.Text + "')";
                dbcom = new OleDbCommand(q, con);
                dbcom.ExecuteNonQuery();
                MessageBox.Show("New Employee '" + tb_name.Text + "'- Successfuly Added.");

            }
        }
        else
        { MessageBox.Show("Employee name '" + tb_name.Text + "' already added into the database"); }
        ds.Dispose();
    }

I'm using Microsoft Access 2010 as my database and this is stand alone system. Please help me.

© Stack Overflow or respective owner

Related posts about c#

Related posts about ms-access