Cara Membuat Kode Otomatis Berdasarkan Kriteria

 

 

 

Imports System.Data.OleDb

 

Public Class Form1

 

    Dim conn As OleDbConnection

    Dim da As OleDbDataAdapter

    Dim ds As DataSet

    Dim cmd As OleDbCommand

    Dim dr As OleDbDataReader

 

    Sub Koneksi()

        conn = New OleDbConnection("provider=microsoft.ace.oledb.12.0;data source=database1.accdb")

        conn.Open()

    End Sub

 

    Sub Kosongkan()

        ComboBox1.Text = ""

        TextBox1.Clear()

        TextBox2.Clear()

        ComboBox1.Focus()

    End Sub

 

    Sub Baru()

        ComboBox1.Text = ""

        TextBox1.Clear()

        TextBox2.Clear()

        ComboBox1.Focus()

    End Sub

 

    Sub CariKode()

        On Error Resume Next

        cmd = New OleDbCommand("select * from tbbarang where left(kode,1)='" & ComboBox1.Text & "' order by kode desc", conn)

        dr = cmd.ExecuteReader

        dr.Read()

        If Not dr.HasRows Then

            TextBox1.Text = ComboBox1.Text + "0001"

        Else

            TextBox1.Text = ComboBox1.Text + Format(Microsoft.VisualBasic.Right(dr(1), 4) + 1, "0000")

        End If

    End Sub

 

    Sub Tampilgrid()

        da = New OleDbDataAdapter("select * from tbbarang", conn)

        ds = New DataSet

        da.Fill(ds)

        DGV.DataSource = ds.Tables(0)

        DGV.ReadOnly = True

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Me.CenterToScreen()

        Call Koneksi()

        Call Tampilgrid()

        ComboBox1.Items.Add("A")

        ComboBox1.Items.Add("B")

        ComboBox1.Items.Add("C")

    End Sub

 

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged

        Call CariKode()

    End Sub

 

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

        Try

            Dim simpan As String = "insert into tbbarang values ('" & ComboBox1.Text & "','" & TextBox1.Text & "','" & TextBox2.Text & "')"

            cmd = New OleDbCommand(simpan, conn)

            cmd.ExecuteNonQuery()

            Call Kosongkan()

            Call Tampilgrid()

        Catch ex As Exception

            MsgBox(ex.Message)

        End Try

    End Sub

 

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

        Call Kosongkan()

 

    End Sub

 

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click

        Me.Close()

    End Sub

End Class