What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 8897 |  Welcome, Guest!   Register  Login
Home > Articles > ADO.NET > How to check for the existence of record into the database?

How to check for the existence of record into the database?

1 vote(s)
Rating: 5 out of 5
Article posted by Sheonarayan on 9/12/2011 | Views: 7361 | Category: ADO.NET | Level: Intermediate | Points: 250 red flag


In this article, we shall learn How to check for the existence of record into the database.

Introduction

ADO.NET is a data access mechanism to communicate with the data sources such as SQL server, XML, ODBC & OLEDB data sources. It allows us to work in connected (database connection is alive while the operation is performed) as well as disconnected architecture (database connection is closed and operation can be performed on the in-memory data).

Get hundreds of ASP.NET Tips and Tricks and ASP.NET Online training here.

In order to check whether a record exists into the database or not, we can follow this approach.

Below is my ASPX code that contains a simple form.

ASPX PAGE

<h3>Check for the existence of the record</h3>

<table cellpadding="3" cellspacing="1">

<tr><td>First name: </td><td><asp:TextBox ID="txtFirstName"

runat="server" /> </td></tr>

<tr><td>Last name: </td><td><asp:TextBox ID="txtLastName" runat="server"

/> </td></tr>

<tr><td>&nbsp;</td><td><asp:Button ID="btnSubmit" runat="server"

Text="Submit" OnClick="CheckRecord" /></td></tr>

</table>

<p><asp:Label ID="lblMessage" runat="server" EnableViewState="false"

ForeColor="Red" /></p>

In the above code snippet we have a two textboxes and a button.

CODE BEHIND

string _connStr =

ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

 

 

protected void CheckRecord(object sender, EventArgs e)

{

// get the connection

using (SqlConnection conn = new SqlConnection(_connStr))

{

// write the sql statement to execute

string sql = "SELECT AutoId FROM PersonalDetail WHERE FirstName = @FirstName

AND LastName = @LastName";

 

// instantiate the command object to fire

using (SqlCommand cmd = new SqlCommand(sql, conn))

{

// attach the parameter to pass, if no parameter is in the sql no need to

attach

SqlParameter[] prms = new SqlParameter[2];

prms[0] = new SqlParameter("@FirstName", SqlDbType.VarChar, 50);

prms[0].Value = txtFirstName.Text.Trim();

prms[1] = new SqlParameter("@LastName", SqlDbType.VarChar, 50);

prms[1].Value = txtLastName.Text.Trim();

 

cmd.Parameters.AddRange(prms);

conn.Open();

object obj = cmd.ExecuteScalar();

conn.Close();

 

if (obj != null)

{

lblMessage.ForeColor = System.Drawing.Color.Green;

lblMessage.Text = "Record exists and its AutoID is : " +

obj.ToString();

}

else

{

lblMessage.Text = "Record doesn't exists.";

}

}

}

}

On the click of the button, CheckRecord method executes. In this method, we have done almost same as we had done for the Insert method in the NormalCURD.aspx (in earlier article) page but instead of calling the ExecuteNonQuery method it calls ExecuteScalar method that returns an object (the first column of the first row of the result set returned by the SELECT statement), if no record is returned by the SELECT statements it returns NULL.

We can check for that object, if it is null then no record exists otherwise that record exists.

OUTPUT

Note: This is very frequently used to validate the credential (Username and Password) of the user in the Login Form.

Hope this was useful. Thanks for reading !

I have received many good feedback about my article series. Thanks to all of you for your support and keep supporting us. Do not forget to refer your friends about these articles, in this way you would be helping him/her to remain and excel in his/her job ! 

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Microsoft_MVP] [Administrator]
Biography:Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001.

Connect me on Facebook | Twitter | LinkedIn | Blog

>> Write Response - Respond to this post and get points
Related Posts

This is the Part 2 of ADO.NET. In this section we will touch base on one of important concepts in ADO.NET.

In different ways, dataadapter.Fill() method can be overridden. In this article, i have tried to elaborate this. Here all the 5 different ways has been explained with code and snap shots.

In this article, we shall learn how to retrieve the saved images from the SQL Server database and show them on the page.

In this article, I am going to show how to use Connection object efficiently and what are the standard practices we should follow while working with connection objects.

In this article I am going to explain how to take backup of your database from ASP.NET or from C#.NET.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/25/2013 6:27:48 PM