Programming for Everybody: Solve Violation of PRIMARY KEy
Showing posts with label Solve Violation of PRIMARY KEy. Show all posts
Showing posts with label Solve Violation of PRIMARY KEy. Show all posts

Visual Basic.net: Insert data into sql Database and Solve Violation of PRIMARY KEY

 


:Source code

Imports System.Data.SqlClient


Public Class Form4

    Dim con1 As SqlConnection = New SqlConnection("Data Source=.;Initial Catalog=users;Integrated Security=True")


    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click


        con1.Open()

        Dim cmd2 As New SqlCommand("Select name1,username1 from table1 where username1=@username1", con1)


        cmd2.Parameters.AddWithValue("@username1", TextBox2.Text)

        Dim myreader As SqlDataReader

        myreader = cmd2.ExecuteReader()

        If (myreader.Read()) Then

            con1.Close()

            MessageBox.Show("Duplicate Username")

            con1.Close()

        Else

           con1.Close()

            Dim strsql As String


            strsql = " Insert into table1(name1,username1) Values(@name,@username)"


            Dim cmd1 As New SqlCommand(strsql, con1)


            cmd1.Parameters.AddWithValue("@name", TextBox1.Text)

            cmd1.Parameters.AddWithValue("@username", TextBox2.Text)


            con1.Open()

            cmd1.ExecuteNonQuery()

            con1.Close()

            MessageBox.Show(" insert successful")


        End If


    End Sub

End Class