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();
}
VulpesPosted Jan 27, 2014, 3:38 PM
Marvin GapuzPosted Feb 20, 2019, 12:59 AM
Vance Keizer BacarraPosted Sep 8, 2015, 4:44 AM
Shourya VerdhanPosted Dec 24, 2014, 12:06 AM
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
}
VulpesPosted Jan 27, 2014, 5:50 PM
if (numRecords == 0)
mind controllPosted Jan 27, 2014, 5:41 PM
if (numrecords == 0)
mind controllPosted Jan 27, 2014, 2:09 PM
shahidkamal ansariPosted Jan 26, 2014, 9:23 PM
.
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.
VulpesPosted Jan 26, 2014, 5:41 PM