0

what's wrong with my code?I just want to add data into access database but it show ExecuteNonQuery:

Connection property has not been initialized.

It's pretty weird because in other project code similar to this works just fine.

OleDbCommand command = new OleDbCommand();
OleDbConnection connect = new OleDbConnection();
OleDbDataReader reader;

    public Absen()
    {
        InitializeComponent();
    }

    MainForm form_utama;

    private void Absen_Load(object sender, EventArgs e)
    {
        connect.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Visual Studio Project\Minor baru - back up\Minor baru\Absensi.accdb;Persist Security Info=False;";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (idkaryawantxt.Text != "")
        {
            string q = "insert into tableAbsensi (ID,ID_divisi,Waktu,Tanggal) values ('" + idkaryawantxt.Text.ToString() + "','" + iddivisitxt.Text.ToString() + "','" + (DateTime.Now.ToString("hh:mm :")) + "','" + (DateTime.Now.ToString("MM-dd-yyyy")) + "')";
            dosomething(q);
        }
    }

    private void dosomething(String q)
    {
        try
            {
                connect.Open();
                command.CommandText = q;
                command.ExecuteNonQuery();
                connect.Close();
            }
            catch (Exception e)
            {
                connect.Close();
                MessageBox.Show(e.Message.ToString());
            }
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
wendy
  • 161
  • 3
  • 14

1 Answers1

4

You didn't set your Command's Connection property

command.Connection = connect;

Before execute your command you should set it as the error said

Selman Genç
  • 100,147
  • 13
  • 119
  • 184