Click here to Skip to main content
15,886,075 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Honors!

Am Veeramanikandan, beginner of .NET Environment.

I would like insert the values into table without Duplicates.

So I want to know how to check whether given ID is Exist or Not in Database in ASP.NET using C#.

Thanks in Advance..

Regards,

Veeramanikandan.D
Posted
Comments
Prasanta_Prince 9-Jun-11 7:26am    
Incase of ID . Try to use Identity.

Heres the query:

string query = string.Format("SELECT id from table where id = {0}", myID);
 
Share this answer
 
Comments
Andrew Rissing 1-Jun-10 20:05pm    
Just a side comment, if "myID" is a string. Use a SQL parameter, rather than just concatenating the string directly yourself, otherwise you open yourself up for SQL injection.
JV9999 17-Jun-11 9:58am    
That's not an answer I would suggest to a beginner for the reasons Andrew mentioned. Also using an Identity column and letting the database decide the ID probably is a better fit.
#realJSOP 17-Jun-11 10:55am    
He wanted to know how to find out if the id exists. That's all that query does. If the ID exists, it's returned. Otherwise, it's null. Yes, he should have an identity column, but that wasn't his question. Your 1-vote (if it was you) is invalid.
jst make the id as PRIMARY KEY in the database or you can also make it as UNIQUE KEY
 
Share this answer
 
try this :-

SqlCommand comd = new SqlCommand("SELECT id from table where id =1",connection);
              string strID=  comd.ExecuteScalar().ToString();
if(strID==""){MessageBox.Show("ID not Found !!");}else{MessageBox.Show("ID Already Exits !!");}
 
Share this answer
 
Like the others said query for it.

but the best is to add a key,
you should probably not make it a primary key if you ever want to change the data value.
 
Share this answer
 
But if i want to show a message that is ....


if primary already exist in database then
{
Key Already Exist
}

plz send me the complete code I m a new in C#.net
 
Share this answer
 
Comments
Simon_Whale 17-Jun-11 9:52am    
I would have a good look at this site

http://msdn.microsoft.com/en-gb/beginner/default.aspx
If I understand correctly, you want to take the highest ID and add it one.
If so, use this query:
SELECT MAX(ID) AS ID FROM table

This give you the highest ID in the table (Of course ID column's type should be a integer).
 
Share this answer
 
Use this code

SQL
string query = string.Format(@"IF EXISTS (SELECT NULL FROM Table WHERE ID = {0})
SELECT 'Key Already Exists'
ELSE
SELECT 'Key Not Found'", myID);



Hope this will help...

Thanks
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900