2 Replies - 438 Views - Last Post: 22 August 2011 - 01:01 AM Rate Topic: -----

#1 coder_d  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 21-August 11

How to prevent a repeat value found in the database

Posted 21 August 2011 - 10:51 PM

Hello
I want to enter a value in a text box to add it in the database, but this value may be found already in the database
This code adds data from text box to the database, but without solving the problem of repetition of the same value that already exist in the database

   private void button1_Click(object sender, EventArgs e)
        {
            
                da.InsertCommand = new SqlCommand("INSERT INTO MyTable VALUES(@Username,@Password)", sc);
                da.InsertCommand.Parameters.Add("@Username", SqlDbType.VarChar).Value = textBox1.Text;
                da.InsertCommand.Parameters.Add("@Password", SqlDbType.VarChar).Value = textBox2.Text;
                sc.Open();
                da.InsertCommand.ExecuteNonQuery();
                sc.Close();
            
        }

Please help

Is This A Good Question/Topic? 0
  • +

Replies To: How to prevent a repeat value found in the database

#2 Joyal1234  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 21-August 11

Re: How to prevent a repeat value found in the database

Posted 21 August 2011 - 11:09 PM

The below logic can work for you:
1. The database table column can be made primary key(if possible in your application)
2. If the entered value is repeated, SQL exception will be thrown that can be handled in the catch block where you can call the code of entering the value again.

Suggestions are invited on my solution.

This post has been edited by Joyal1234: 21 August 2011 - 11:10 PM

Was This Post Helpful? 0
  • +
  • -

#3 andy_pleasants  Icon User is offline

  • D.I.C Head

Reputation: 41
  • View blog
  • Posts: 122
  • Joined: 08-July 10

Re: How to prevent a repeat value found in the database

Posted 22 August 2011 - 01:01 AM

Alternatively you can just enforce a unique key constraint on that column. It doesn't have to be your primary key then, but will need to be unique
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1