Vb.net Billing Software Source Code [top] Jun 2026
Automatically lower stock counts when an invoice is finalized. Print Preview: Generate a clean, printable receipt layout. 1. Database Architecture (SQL Server)
: Implements foreign key constraints between products, customers, and invoice tables. vb.net billing software source code
Imports System.Data.SqlClient Public Class dbConfig Public conn As New SqlConnection("Data Source=YOUR_SERVER;Initial Catalog=BillingDB;Integrated Security=True") Public Sub OpenConnection() If conn.State = ConnectionState.Closed Then conn.Open() End Sub Public Sub CloseConnection() If conn.State = ConnectionState.Open Then conn.Close() End Sub End Class Use code with caution. 4. Designing the Billing UI Your main form ( frmBilling.vb ) should include: Product ID, Quantity, Price, Customer Name. DataGridView: To display the current items in the cart. Buttons: "Add to Cart", "Generate Invoice", "Clear". 5. Core Logic: Adding Items to Grid Automatically lower stock counts when an invoice is
Implement a prior conditional evaluation inside btnAddToGrid_Click that references database stock levels. If StockQuantity - RequestedQuantity < 0 , flag a system warning to block sales when inventory is insufficient. Database Architecture (SQL Server) : Implements foreign key
: Automatically updates stock levels when an invoice is finalized.
Imports System.Data.SqlClient Imports System.Configuration Public Class frmBilling ' Retrieve connection string from App.config Private connString As String = ConfigurationManager.ConnectionStrings("BillingDBConn").ConnectionString Private selectedProductID As Integer = 0 Private Sub frmBilling_Load(sender As Object, e As EventArgs) Handles MyBase.Load ConfigureDataGridView() GenerateInvoiceNumber() End Sub ' Configure DataGridView columns programmatically Private Sub ConfigureDataGridView() dgvItems.Columns.Clear() dgvItems.Columns.Add("ProductID", "ID") dgvItems.Columns.Add("ProductCode", "Code") dgvItems.Columns.Add("ProductName", "Product Name") dgvItems.Columns.Add("Price", "Unit Price") dgvItems.Columns.Add("Qty", "Quantity") dgvItems.Columns.Add("Total", "Total Price") dgvItems.Columns("ProductID").Visible = False dgvItems.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill End Sub ' Generate a unique sequential Invoice Number Private Sub GenerateInvoiceNumber() Using conn As New SqlConnection(connString) Dim query As String = "SELECT TOP 1 InvoiceID FROM Invoices ORDER BY InvoiceID DESC" Using cmd As New SqlCommand(query, conn) Try conn.Open() Dim obj As Object = cmd.ExecuteScalar() If obj IsNot Nothing AndAlso Not IsDBNull(obj) Then Dim nextId As Integer = Convert.ToInt32(obj) + 1 txtInvoiceNo.Text = "INV-" & nextId.ToString("D5") Else txtInvoiceNo.Text = "INV-00001" End If Catch ex As Exception MessageBox.Show("Error generating invoice number: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Using End Using End Sub ' Search Product by Code when user presses Enter Private Sub txtProductCode_KeyDown(sender As Object, e As KeyEventArgs) Handles txtProductCode.KeyDown If e.KeyCode = Keys.Enter Then If String.IsNullOrWhiteSpace(txtProductCode.Text) Then Exit Sub Using conn As New SqlConnection(connString) Dim query As String = "SELECT ProductID, ProductName, UnitPrice FROM Products WHERE ProductCode = @Code" Using cmd As New SqlCommand(query, conn) cmd.Parameters.AddWithValue("@Code", txtProductCode.Text.Trim()) Try conn.Open() Using reader As SqlDataReader = cmd.ExecuteReader() If reader.Read() Then selectedProductID = Convert.ToInt32(reader("ProductID")) txtProductName.Text = reader("ProductName").ToString() txtPrice.Text = Convert.ToDecimal(reader("UnitPrice")).ToString("F2") txtQuantity.Focus() Else MessageBox.Show("Product not found.", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Warning) ClearProductFields() End If End Using Catch ex As Exception MessageBox.Show("Database error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Using End Using e.SuppressKeyPress = True End If End Sub ' Add calculated row to the DataGridView Private Sub btnAddToCart_Click(sender As Object, e As EventArgs) Handles btnAddToCart.Click If selectedProductID = 0 OrElse String.IsNullOrWhiteSpace(txtQuantity.Text) Then MessageBox.Show("Please select a valid product and enter quantity.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If Dim qty As Integer Dim price As Decimal If Not Integer.TryParse(txtQuantity.Text, qty) OrElse qty <= 0 Then MessageBox.Show("Quantity must be a positive integer.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If price = Convert.ToDecimal(txtPrice.Text) Dim total As Decimal = price * qty ' Check if product already exists in the grid; if so, update quantity Dim itemExists As Boolean = False For Each row As DataGridViewRow In dgvItems.Rows If Convert.ToInt32(row.Cells("ProductID").Value) = selectedProductID Then Dim currentQty As Integer = Convert.ToInt32(row.Cells("Qty").Value) Dim newQty As Integer = currentQty + qty row.Cells("Qty").Value = newQty row.Cells("Total").Value = (newQty * price).ToString("F2") itemExists = True Exit For End If Next If Not itemExists Then dgvItems.Rows.Add(selectedProductID, txtProductCode.Text.Trim(), txtProductName.Text.Trim(), price.ToString("F2"), qty, total.ToString("F2")) End If CalculateInvoiceTotals() ClearProductFields() txtProductCode.Focus() End Sub ' Calculate Subtotal, Tax, and Grand Total Private Sub CalculateInvoiceTotals() Dim subTotal As Decimal = 0 For Each row As DataGridViewRow In dgvItems.Rows If Not row.IsNewRow Then subTotal += Convert.ToDecimal(row.Cells("Total").Value) End If Next Dim taxRate As Decimal = 0.15D ' 15% Tax Rate Example Dim taxAmount As Decimal = subTotal * taxRate Dim grandTotal As Decimal = subTotal + taxAmount txtSubTotal.Text = subTotal.ToString("F2") txtTax.Text = taxAmount.ToString("F2") txtGrandTotal.Text = grandTotal.ToString("F2") End Sub ' Commit Customer, Invoice Master, and Invoice Details to DB using a SQL Transaction Private Sub btnSaveInvoice_Click(sender As Object, e As EventArgs) Handles btnSaveInvoice.Click If dgvItems.Rows.Count = 0 Then MessageBox.Show("Cart is empty. Cannot save invoice.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If If String.IsNullOrWhiteSpace(txtCustomerName.Text) Then MessageBox.Show("Customer Name is required.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning) Exit Sub End If Using conn As New SqlConnection(connString) conn.Open() Dim trans As SqlTransaction = conn.BeginTransaction() Try ' 1. Insert Customer Data Dim customerId As Integer Dim custQuery As String = "INSERT INTO Customers (CustomerName, ContactNumber, Address) OUTPUT INSERTED.CustomerID VALUES (@Name, @Contact, @Address)" Using cmdCust As New SqlCommand(custQuery, conn, trans) cmdCust.Parameters.AddWithValue("@Name", txtCustomerName.Text.Trim()) cmdCust.Parameters.AddWithValue("@Contact", If(String.IsNullOrWhiteSpace(txtContact.Text), DBNull.Value, txtContact.Text.Trim())) cmdCust.Parameters.AddWithValue("@Address", If(String.IsNullOrWhiteSpace(txtAddress.Text), DBNull.Value, txtAddress.Text.Trim())) customerId = Convert.ToInt32(cmdCust.ExecuteScalar()) End Using ' 2. Insert Invoice Master Record Dim invoiceId As Integer Dim invQuery As String = "INSERT INTO Invoices (InvoiceNumber, CustomerID, SubTotal, TaxAmount, GrandTotal) OUTPUT INSERTED.InvoiceID VALUES (@InvNum, @CustID, @Sub, @Tax, @Grand)" Using cmdInv As New SqlCommand(invQuery, conn, trans) cmdInv.Parameters.AddWithValue("@InvNum", txtInvoiceNo.Text.Trim()) cmdInv.Parameters.AddWithValue("@CustID", customerId) cmdInv.Parameters.AddWithValue("@Sub", Convert.ToDecimal(txtSubTotal.Text)) cmdInv.Parameters.AddWithValue("@Tax", Convert.ToDecimal(txtTax.Text)) cmdInv.Parameters.AddWithValue("@Grand", Convert.ToDecimal(txtGrandTotal.Text)) invoiceId = Convert.ToInt32(cmdInv.ExecuteScalar()) End Using ' 3. Insert Child Rows & Update Stock Levels Dim detailQuery As String = "INSERT INTO InvoiceDetails (InvoiceID, ProductID, Quantity, Price, Total) VALUES (@InvID, @ProdID, @Qty, @Price, @Total)" Dim stockQuery As String = "UPDATE Products SET StockQuantity = StockQuantity - @Qty WHERE ProductID = @ProdID" For Each row As DataGridViewRow In dgvItems.Rows If Not row.IsNewRow Then Dim prodId As Integer = Convert.ToInt32(row.Cells("ProductID").Value) Dim qty As Integer = Convert.ToInt32(row.Cells("Qty").Value) Dim price As Decimal = Convert.ToDecimal(row.Cells("Price").Value) Dim total As Decimal = Convert.ToDecimal(row.Cells("Total").Value) ' Save line details Using cmdDet As New SqlCommand(detailQuery, conn, trans) cmdDet.Parameters.AddWithValue("@InvID", invoiceId) cmdDet.Parameters.AddWithValue("@ProdID", prodId) cmdDet.Parameters.AddWithValue("@Qty", qty) cmdDet.Parameters.AddWithValue("@Price", price) Use code with caution.
Add items to a data grid with real-time calculation of subtotals, tax, discounts, and grand totals.