.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Check if record exists in mssql database c# code

Posted By:      Posted Date: April 10, 2011    Points: 0   Category :ASP.Net

Hello everyone!

I coded this page a while back, but I'm thinking there must be a better way to do this.  What I want to do is check real-time if various records exist in my database from a function in my C# code.  What I've done is added a sqldatabase onto my page, as well as a gridview.  Here is what I have done to verify if a record exists.

public bool RecordExists(string gName, DateTime gDate)
        // Set default to false
        bool returnBool = false;
        SqlDataSourceEvents.SelectCommand = "SELECT ID, StartTime, EndTime, EventName, UserID, Details FROM EventTable WHERE (DATEPART(day, StartTime) = DATEPART(day, '" + gDate.ToString() + "')) AND (UserID='" + gName + "')";

        for (int i = 0; i < GridViewEvents.Rows.Count; i++)
            if (DateTime.Parse(GridViewEvents.Rows[i].Cells[0].Text) == gDate)
                if (GridViewEvents.Rows[i].Cells[2].Text == gName)
                    returnBool = true;
        // Return SqlDataSourceEvents to original state
        SqlDataSourceEvents.SelectCommand = "SELECT ID, StartTime, EndTime, EventName, UserID, Details FROM EventTable WHERE (DATEPART(month, StartTime) = 

View Complete Post

More Related Resource Links

Can this code be setup to run against the whole database instead of just 1 record at a time?


We have made some changes to this code to start capturing 1 new field of data and updating it as new records are added. But there is currently about 120,000 records more or less.. those records of course dont have the new field populated with anything..

We would like to run this logic that already in place and run it against the tables to update the fields 1 time. I think to make it easier, if it can be setup to expect the "valueTwo" variable, so that we can run it againt the individual codes instead of doing all the records at one time.. there are codes that only have a few records, so it would be best to test initially against the small code group.


            strSqual = "insert into trans (trans_type_name, trans_date,sys_id,mod_user_id,show_ind, remoteCode, techName) values('" & valueTwo & "','" & TransDate & "',"&strSystemID&", 1,'T', '" & dbQuote(strUser) & "', '" & strTechName & "')"        
            'get the new transaction_id out for just inserted alarm   
            strSqual = "select max(transaction_id) as transaction_id from trans"  
            set rst = getStaticRecordSet(strSqual)

How to check if record is added in access database



I'm trying to put a registration page together in Visual Web Designer.

I would like to send a confirmation Email after someone is leaving his registration data and pressing the INSERT button.

The key fields in my database are: Email, Name, Surname, Address

Before I send the confirmation Email I would like to check if the email value entered in the form is realy added to the database.

Please for help in this matter. I was copy past already some C code in my page, therefore it will be fine if the code can be in C.

Again, I need help to:

- checking if record is realy added to database after pressing INSERT button

- setup the confirmation Email

Thank you in advance.


How can i check if record already exist in sql-server database ...

How can i check if record already exist in sql-server database ...

C# How to check prammatically if null value exists in database table (using stored procedure)?


How to programattically check if null value exists in database table (using stored procedure)?

I know it's possble in the Query Analyzer (see last SQL query batch statements)?

But how can I pass null value as parameter to the database stored procedure programattically using C#?

Although I can check for empty column (the following code passes string.Empty as parameter but how to pass null value?), I cannot check for null value in the following code snippet:

SQL Queries:

USE [master]

IF EXISTS (SELECT name FROM sys.databases WHERE name = 'ExampleDatabase')
DROP DATABASE [ExampleDatabase];

CREATE DATABASE [ExampleDatabase];

USE [ExampleDatabase];

DROP TABLE dbo.ExampleTable;

IsActive BIT,


Check to see if record exists befor SQL Insert


I would like to check and see if a record exists before doing an insert. Here is the code I have tried:


Imports System.Data
Imports System.Data.SqlClient
Imports Telerik.Web.UI
Imports System.CodeDom
Imports System.Web
Imports System.Web.Security
Imports System.Web.Security.Roles
Imports System.Web.Security.Membership
Imports System.Security
Imports System.Security.Principal.WindowsIdentity

Partial Class template
    Inherits System.Web.UI.Page
    Private Shared prevPage As String = String.Empty

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If (Not IsPostBack) Then
            prevPage = Request.UrlReferrer.ToString()
        End If
    End Sub

    Protected Sub btn_Volunteer_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim IDProfileVolunteer As String = Session("IDProfileVolunteer")
        Dim IDProfileOrganization As String = CType(FormView1.FindControl("hf_IDProfileOrganization"), HiddenField).Value

        Dim conn As SqlConnection
        Dim cmd As SqlCommand
        Dim strconnection, strsqlinsert As String

        Dim currentUser As MembershipUser = Membership.GetUser()
        Dim currentUserId As Gu

Check if DataBase Exists


I have the following function coding in VB 2010 but it always returns a value of false.  Is there something wrong with my SQL code to check if a database exists?

 Public Function CheckDBExists(ByVal ConnString As String, ByVal databasename As String) As Boolean

        Dim exists As Byte = 0

        Dim conn As SqlConnection = New SqlConnection(ConnString)

        Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'" & databasename & "')", conn)


        exists = CByte(cmd.ExecuteScalar())


        Return CBool(exists)

    End Function

Dennis in Longview

Does this look correct for saving a file/ new record to a database


So thank you for all your help so far, So I think i got this right,
but would like for you all to look it over to see if there is any
areas I might run into trouble with:

//using asp.net mvc 2
the table (sql server 2005, using entities framework)
table fields
"Pattern_Media_GUID  uniqueid 
"Pattern_GUID  uniqueid
"Media varbinary(max)  
"height int
"Width int
"Media_Type String (50)

the form:
<h2> Add Media to this pattern</h2>
<% Html.EnableClientValidation(); %>
<% Html.BeginForm("AddMedia", "Pattern", new { id= Model.Pattern_Guid} , FormMethod.Post, new {enctype = "multipart/form-data"}); %>
    <%: Html.Label("height") %>
    <%: Html.TextBox("height") %>

    <%: Html.Label("width") %>
    <%: Html.TextBox("width") %>

    <%: Html.Label("Media") %>
    <input type="file" id="Media" name="Media" />
    <input type="submit" name=

Create/add table from code to database



I create table:

                  DataSet data=new DataSet();

                  DataTable myTable = new DataTable("NewTable");

                   DataColumn[] keys = new DataColumn[1];

                   // create column
                   keys[0] = new DataColumn();
                   keys[0].DataType = System.Type.GetType("System.String");
                   keys[0].ColumnName = "PointID";
                   myTable.Columns.Add(keys[0]);    &nb

Under the Table: How Data Access Code Affects Database Performance


In this article, the author delves into some commonly used ways of writing data access code and looks at the effect they can have on performance.

Bob Beauchemin

MSDN Magazine August 2009

Toolbox: Database Audit Logs, Joel on Software, Code Handouts, and More


This month the Toolbox column takes a look at database logging, Joel Spolsky's blog, printing code projects, and ASP.NET reading.

Scott Mitchell

MSDN Magazine May 2008

Protect It: Safeguard Database Connection Strings and Other Sensitive Settings in Your Code


Protecting application secrets, such as database connection strings and passwords, requires careful consideration of a number of pertinent factors such as how sensitive the data is, who could gain access to it, how to balance security, performance, and maintainability, and so forth. This article explains the fundamentals of data protection and compares a variety of techniques that can be used to protect application settings. The author discusses what to avoid, such as hiding keys in source code and the use of Local Security Authority. In addition, he presents some effective solutions such as the Data Protection API.

Alek Davis

MSDN Magazine November 2003

Wicked Code: Supporting Database Cache Dependencies in ASP.NET


Developers love the ASP. NET application cache. One reason they love it is that ASP. NET lets them create dependencies between items placed in the cache and files in the file system. If a file targeted by a dependency changes, ASP.

Jeff Prosise

MSDN Magazine April 2003

>>>Check duplicate while inserting record from Texbox.

Hi, On inserting record, I want to check that for example if a user enters a telephone number for any record is already in the database then it should validate that the number already exists in table and you cannot enter a duplicate value. Then if user will provide some other telephone number then he allows to insert record. For insertion of record I used ObjectdataSource. User will enter telephone number in a simple textbox. I may want to inform that I am working in asp.net2.0 and also not allowed to use any third party control or ajaxtoolkit. Any idea would be appreciated.

Get last record in a SQL database

Don't know if this is the right SQL section, but... using VBE, how do you SQL for the last record in the database?Thanks.

[C#] Database ".mdf" already exists. Choose a different database name.

Hi all, it's all day long that i'm fighting with this problem. And i'm getting quite upset! SHORT VERSION Why when i call DataContex.CreateDatabase() does SQLExpress 2008 say that the file already exist even if the file is completly wiped form the DISK!?!   LONG VERSION So, what i'm trying to do is damn simple. I'm developing a simple web application. To do that i've built a DBML file to use with LINQ. For development purpose i'd like to create a local DB. So here my code: string connectionString = ConfigurationManager.ConnectionStrings["PermissionsDatabase"].ConnectionString; Response.Write(connectionString); using (PermissionDataContext dataContext = new PermissionDataContext(connectionString)) { if (!dataContext.DatabaseExists()) { dataContext.CreateDatabase(); } }   And in the web.config the connection strin is: Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Projects\AccessControl\WebSite\App_Data\permissions.mdf;Integrated Security=True;User Instance=True When the CreateDatabase() is called i get that Exception. Where the ____ do SQLServer keeps track of that file?! Why if the database already exists the DatabaseExists() return false?!   Moreover if i use this connection string: Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\permissions.mdf;Integrated Security=True;User Instance=True

Is there a way to check if workflow instance already exists for a particular productID in Workflow o

I am using Visual Studio 2008 and .NET 3.5. I am trying to build a WF that is exposed as WCF hosted on IIS. This service is consumed by ASP.NET client. It is a very simple WF- receive info for new product "A"- send email to person 'Xyz' that new prodcut "A" is received- do some business process for product "A"- send out more notifications for product "A"Consider this scenario - - Client hits submit on asp.net page for prodcut "A"- new WF instance is created for product "A"- client can go back to the same page, edit some more info and hit save again. However, this time or for any subsequent "Saves",  I do not want to create a new WF instance for product "A".I can check to see if a WF instance exists for product "A" on the client side before calling the service operation. However, I want to see if there is a way to do this in WF or WorkflowServiceHost, as I don't want to add this logic to client. First acitvity in WF has to be receive activity with CanCreateInstance = true, so not sure how I can do this check in WF itself.Also, I have another stupid question, when using WF exposed as WCF service, do we have to implement all service operations using WF? What if I have some service operations that just involves checking some business logic? Do I implement this in a

LinQ to check if xml node exists in the XML??

Using LinQ or any C# syntax, I just want to know whether "Item" Child exists or not if the parent Node (ChildMenuSelected>>MenuSelected) are true from the below xml format.Xml Format:<MenuDataResult> <Items> <Item> <ItemType>Submenu</ItemType> <ItemTitle>Level22</ItemTitle> <Menu> <MenuSelected>false</MenuSelected> <ChildMenuSelected>false</ChildMenuSelected> </Menu> </Item> <Item> <ItemType>Submenu</ItemType> <ItemTitle>Level21</ItemTitle> <Menu> <MenuSelected>false</MenuSelected> <!--if ChildMenuSelected = true --> <ChildMenuSelected>true</ChildMenuSelected> <Item> <ItemType>Submenu</ItemType> <ItemSubType>0</ItemSubType> <Menu> <!--if MenuSelected = true --> <MenuSelected>true</MenuSelected> <ChildMenuSelected>false</ChildMenuSelected> <!-- whether this below item exists or not --> <Item> <ItemType>Submenu</ItemType> <Menu> <MenuSelected>false</MenuSelected> <ChildMenuSelected
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend