Sunday 13 January 2013

Check for duplicate data in database

I will show you how to check duplicate in database table before inserting into database.

For that follow database design from my previous example (display image in gridview).

Now Write a function which will return true/false.(bool value)
-------------------------------------------------

 private bool IsPictureExists(string name)
        {
            string constring = @"Server=User-PC\SQLEXPRESS;initial catalog=Student;Integrated Security=true";
            SqlConnection conn = new SqlConnection(constring);
            conn.Open();
            string query="Select count(ImageName) from  [student].[dbo].[ImageTable] where ImageName= '" + name.Text +"'";
            SqlCommand cmd = new SqlCommand(query, conn);
            int i = (int)cmd.ExecuteScalar();
            if (i ==0)
            {
                return true;
            }
            return false;
        }
------------------------------------------------------
Now call this function on button click like


 protected void Button1_Click(object sender, EventArgs e)
        {
           if(IsPictureExists(name).Equals(true))
           {
       //Insert Logic goes here
           }
         else
      //Show message - Duplictaed..
That's it.

No comments:

Post a Comment