Thursday, June 30, 2016

ADD, UPDATE, DELETE FROM Database VB.NET

Imports System.Data

Imports System.Data.SqlClient

ADD
'--------------------------------------------------------------------------------
 Dim xcounter As Integer = 0
        Try
            myconn = New SqlConnection(My.Settings.testsettings)
            myconn.Open()
            mycmd = New SqlCommand("insert into test1 (fname,mname,lname) values ('" & TextBox1.Text & "' , '" & TextBox2.Text & "' , '" & TextBox3.Text & "')", myconn)
            xcounter = mycmd.ExecuteNonQuery
            MessageBox.Show("(" & xcounter & ") affected")
            myconn.Close()
            mycmd.Dispose()
        Catch ex As Exception
            myconn.Close()
            mycmd.Dispose()
            MessageBox.Show(ex.Message)
        End Try
'--------------------------------------------------------------------------------


EDIT
'--------------------------------------------------------------------------------
Dim xcounter As Integer = 0
        Try
            myconn = New SqlConnection(My.Settings.testsettings)
            If myconn.State = System.Data.ConnectionState.Closed Then
                myconn.Open()
            End If

            mycmd = New SqlCommand("update test1 set fname='" & TextBox4.Text & "' , mname='" & TextBox5.Text & "' , lname='" & TextBox6.Text & "' where id ='" & idd & "'", myconn)
            xcounter = mycmd.ExecuteNonQuery
            MessageBox.Show("(" & xcounter & ") affected")

            myconn.Close()
            mycmd.Dispose()

        Catch ex As Exception
            MessageBox.Show(ex.Message, "asdf")
            myconn.Close()
            mycmd.Dispose()


        End Try
'--------------------------------------------------------------------------------


DELETE
'--------------------------------------------------------------------------------
        If MessageBox.Show("Are your sure to delete  '" & DataGridView1.SelectedRows(0).Cells(0).Value & "'", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = Windows.Forms.DialogResult.Yes Then


            Dim xcounter As Integer = 0
            Try
                myconn = New SqlConnection(My.Settings.testsettings)
                myconn.Open()
                mycmd = New SqlCommand("delete from test1 where id='" & idd & "'", myconn)
                xcounter = mycmd.ExecuteNonQuery
                MessageBox.Show("(" & xcounter & ") affected")

            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
            myconn.Close()
            mycmd.Dispose()
            gview()

        End If
'--------------------------------------------------------------------------------

No comments: