I need to prevent inserting duplicated records in a sql table and if exists show message says already exists
this is my button event :
private void button2_Click(object sender, EventArgs e)
{
conn.Open();
com.Connection = conn;
sql = "INSERT INTO lapusers([username],[fillingcode],[branch],[department],[agency])VALUES(@username,@fillingcode,@branch,@department,@agency)";
com.CommandText = sql;
com.Parameters.Clear();
com.Parameters.AddWithValue("@username", userlapbox.Text);
com.Parameters.AddWithValue("@fillingcode", userfilllapbox.Text);
com.Parameters.AddWithValue("@branch", comboBox2.Text);
com.Parameters.AddWithValue("@department", comboBox1.Text);
com.Parameters.AddWithValue("@agency", comboBox3.Text);
com.ExecuteNonQuery();
MessageBox.Show("Created Successfully ..");
conn.Close();
}

VulpesRank #55 · 29.2K reputationPosted Jan 27, 2014, 10:38 AM EST
VulpesRank #55 · 29.2K reputationPosted Jan 26, 2014, 12:41 PM EST
shahidkamal ansari2 reputationPosted Jan 26, 2014, 4:23 PM EST
.
The first one is very simple.
In your database table,identify the primary key or
Composite key depending upon your requirement of
How you define the row as unique.
Then.put your c# code in try catch block.
So when ever you inswrt a duplicate record
Database exception wpuld be thrown which woulde catch
At c# code level
Second method would be simple checking the exitance of the record
In database before inserting the new record. But here there will be two
Database hits.
mind controll144 reputationPosted Jan 27, 2014, 9:09 AM EST
mind controll144 reputationPosted Jan 27, 2014, 12:41 PM EST
if (numrecords == 0)
Shourya Verdhan62 reputationPosted Dec 23, 2014, 7:06 PM EST
There is also a simplest way, Just write this code in your page.
Put This code before the Page_Load
protected void Page_Init(object sender, EventArgs e)
{
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.Cache.SetExpires(System.DateTime.UtcNow.AddSeconds(-1));
Response.Cache.SetNoStore();
}
protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["update"] = Session["update"];
}
Then
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
}
Then at the time of insert the data
if (Session["update"].ToString() == ViewState["update"].ToString())
{
Write your insert Query here
}
Vance Keizer Bacarra2 reputationPosted Sep 8, 2015, 12:44 AM EDT
Marvin Gapuz78 reputationPosted Feb 19, 2019, 7:59 PM EST
VulpesRank #55 · 29.2K reputationPosted Jan 27, 2014, 12:50 PM EST
if (numRecords == 0)