.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 to see if record exists befor SQL Insert

Posted By:      Posted Date: October 13, 2010    Points: 0   Category :ASP.Net

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

View Complete Post

More Related Resource Links

Check if record exists in mssql database c# code


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) = 

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 ...

>>>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.

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

Insert Same Record Multiple Times.

I have a simple form that inserts a record into a SQL table. The fields are: SerialNumTagNumPONumLocationAddressDescription   This works great. However, I have now been asked to have the form insert x number of records at one time. They want to be able to fill out the following fields: PONumLocationAddressDescription and then have texbox where they can add a number and have that number of the same record inserted.    I hope this makes sense.

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

How to check if SPFiled already exists?

hi   I donot know the internal name and cannot use title for retreiving the filed because user can add 2 fields with the same title. Is there anyother option to check if filed already exists?

Record is already exists in Dimension table but still Kimball SCD Component is Identifying it as a n

Hi I have loaded Dimension table. Now even if the record already exists in my dimension table , every time I run package Kimball method SCD component is identifying as a new record. Please advise. Thanks, Anuja

Cannot INSERT record using Asp.Net Dynamic Data Domain Service Web Applications

 Hi, I am working on a 'Asp.Net Dynamic Data Domain Service Web Application' project using just 2 tables, FAQ_Categories and FAQs. The FAQs table has a foreign key to the FAQ_Categories. The steps are straight forward. Add a new project (Asp.Net Dynamic Data Domain Service Web Applications) Add folders Model ( for Linq2Sql datacontext), Domain (for the Domain Services class) Add Linq2Slql and add the 2 tables to the designer. Build the project. Add the Domain Service Class to the Domain folder. in the wizard select the DataContext, uncheck the Enable Client & Expose ODate checkbox Check bothe table & their corresponding Enable Editing tables checbox Check the Generate Metadata class Click OK. In Global.asax set Scaffold to true and add the DomainService name. Build and run.   Pages List and Detail are working fine. But if I try to insert a new record, I get the error "FaqId is required" Faq_ID is the primary key in the database table and it is set to Identiy. The Datacontext is correct, it marked the FAQ table with <Global.System.Data.Linq.Mapping.ColumnAttribute(Storage:="_CustomerId", AutoSync:=AutoSync.OnInsert, DbType:="Int NOT NULL IDENTITY", IsPrimaryKey:=true, IsDbGenerated:=true)> _   I tried this using Linq2Sql, Entity Framework, And both in VB and C# with the same result. I am using VS20

check user exists in which group

After entering user name, i want check user belonging to which group, group is some thing like role based if group is something group1 , then i want redirect hime to page 1, if groupis 2  then page 2 like that

How check if file exists?

Hello I want to delete file, i can do this but firstly i want to check if it exist. What must i add to  my code for this? DECLARE @del varchar(50) SET @del = REPLACE(' del C:\ADFS\Data_'+CONVERT(char(10),dateadd(year,+1,DATEADD(dd, -1, GETDATE())),103)+'.csv','/','.') EXEC master..xp_cmdshell @del

check if a table exists in SQL 2005

I'm trying to check if a certain table exists in a given database on a SQL 2005 Server. I've tried numerous times without any result.   can anyone point me in the right direction?

How to insert a Record as per collections

Table1 valuescol1             col2---------------------------1                abc2                def3                ghi Table2 valuescol1     col2   col3   col41           1      gh     jk-----------------------------------------Now the Problem is in My coding i taken List<string> li=new List<string>();li.Add("abc");li.Add("def");li.Add("ghj");in a Textbox i am entering abc value then it should get it ID value.My Questions areHow should i assign a value of Col2 value of Table1 as per the data values what we are entering ?User is entering "abc" or "def" or "ghj" only not ID values.....What is the code for that?

Check if custom culture exists

Hello, I created a custom culture using the 'Register' method on the CultureAndRegionInfoBuilder class. But if you execute this method when the culture has already been registered, then an exception will be thrown. So, is it possible to check if the culture is already registered on the machine? Regards, Stefan

Formview check for duplicate value before insert

I've looked at some posts on here but I keep getting errors.  I am just trying to see if an email address exists already before the insert and if it does, have a label display that message to the user. From what I read so far, it looks like I could do a query in the ItemInserting event.  I just need help on the code.  Thanks in advance for any help.. Here is the Code Behind.....where I assume I can do the duplicate check in the ItemInserting event... Protected Sub duplicatecheck(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) Handles FormView1.ItemInsertingEnd   End Sub     Here is the formview page...   <%@ Page Language="VB" AutoEventWireup="false" CodeFile="signup.aspx.vb" Inherits="signup" %> <! < <DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">html xmlns="http://www.w3.org/1999/xhtml">head runat="server">   </ <<title></title>head>body>  <form id="form1" runat="server">  <div>      <asp:FormView ID="FormView1" runat="server" DataKeyNames="ID" DataSourceID="SqlDataSource2" Def

Display Inserted Record After Insert Using A FormView

How do I display a record in a FormView once the record has been inserted? I'm able to get the Identity of the new record without anyproblems, but I can't figure out how I should code the _ItemCreated event. Protected Sub FormViewMessageDetail_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertedEventArgs) 'Refresh the list to show the new record RepeaterMessages.DataBind() 'Set the .SelectCommand to Select the New Record SqlDataSourceMessageDetail.SelectCommand = "SELECT * FROM Messages WHERE [Id] = " & NewId FormViewMessage.DataBind() FormViewMessage.ChangeMode(FormViewMode.Edit) test.Text = NewId.ToString End Sub Protected Sub SQLDataSourceMessageDetail_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) NewId = e.Command.Parameters("@NewId").Value End Sub
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