Israel

Israel

  • NA
  • 1.3k
  • 204.7k

What happen with my codes???

Sep 17 2015 5:08 AM
Hi!
 
I wrote these codes to doesnt allow duplication records in my table.  But I have a bugg and displaying error message on this line: 
int numRecords = (int)comm.ExecuteScalar(); 
 
error message: 
ExecuteScalar: Connection property has not been initialized.
 
My codes:
 
private void button1_Click(object sender, EventArgs e)
{
conn = new OleDbConnection(connstr);
comm = new OleDbCommand();
conn.Open();
connstr = "SELECT COUNT(*) FROM Not_duplicated_datas WHERE [username] = @username";
comm.CommandText = connstr;
comm.Parameters.Clear();
comm.Parameters.AddWithValue("@username", textBox1.Text);
int numRecords = (int)comm.ExecuteScalar();// the bugg it's here
if (numRecords == 0)
{
connstr = "INSERT INTO Not_duplicated_datas([username],[fillingcode],[branch],[department],[agency])VALUES(@username,@fillingcode,@branch,@department,@agency)";
comm.CommandText = connstr;
comm.Parameters.Clear();
comm.Parameters.AddWithValue("@username", textBox1.Text);
comm.Parameters.AddWithValue("@fillingcode", textBox2.Text);
comm.Parameters.AddWithValue("@branch", textBox3.Text);
comm.Parameters.AddWithValue("@department", textBox4.Text);
comm.Parameters.AddWithValue("@agency", textBox5.Text);
comm.ExecuteNonQuery();
MessageBox.Show("Created Successfully ..");
}
else
{
MessageBox.Show("A record with a user name of {0} already exists", textBox1.Text);
}
conn.Close();
 
 

Answers (3)