Cefora Kaja

Cefora Kaja

  • NA
  • 19
  • 3.5k

Prevent duplication datas...

Sep 21 2015 6:13 PM
Hi!
 
I have this code to prevent duplicate records but its give me an error message that says:
Object reference not set to an instance of an object. 
 
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.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Dont_save_when_record_duplicated\WindowsFormsApplication1\App_data\test.mdb;Persist Security Info=False");
OleDbCommand comm;
string connstr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Dont_save_when_record_duplicated\WindowsFormsApplication1\App_data\test.mdb;Persist Security Info=False";
public Form1()
{
InitializeComponent();
}
 
 
 
private void button1_Click(object sender, EventArgs e)
{
//conn = new OleDbConnection(connstr);
//comm = new OleDbCommand();
//comm.Connection = conn;
conn.Open();
comm.Connection = conn;
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();
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 (5)