thongkorn โพสต์ 2023-9-9 15:57:21

[VB.NET] โค้ดการคำนวณหาอัตราค่าบริการขนส่งไปรษณีย์ (eCo Post)

โค้ด VB.NET (2010) กับการคำนวณหาอัตราค่าบริการขนส่งไปรษณีย์ (eCo Post) ...

http://www.g2gsoft.com/webboard/images/VBNet/weightcal.png


http://www.g2gsoft.com/webboard/images/VBNet/ecopost.jpg

มาดูโค้ดฉบับเต็มกันเถอะ ...
Public Class frmWeightCalculation

    Private Sub frmWeightCalculation_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
      Select Case e.KeyCode
            Case Keys.F8
                Call DeleteRow("btnDelRow")
            Case Keys.F7
                Call btnAddToDataGridView_Click(sender, e)
                txtWeight.Focus()
      End Select
    End Sub

    Private Sub frmWeightCalculation_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
      Call InitializeGrid()
      Call rdoEnvelope_Click(sender, e)
      Call ClearTextBox()
      txtWeight.Focus()
      txtWeight.Tag = 0
    End Sub

    Private Sub ClearTextBox()
      txtWeight.Text = "0"
      txtPriceEnvelope.Text = "0.00"
      txtPriceBox.Text = "0.00"
      txtPriceEnvelopeBox.Text = "0.00"
      txtWeightDescription.Text = String.Empty
    End Sub

    Private Sub txtWeight_GotFocus(sender As Object, e As System.EventArgs) Handles txtWeight.GotFocus
      If Not IsDBNull(txtWeight.Text) Then
            txtWeight.SelectionStart = 0
            txtWeight.SelectionLength = txtWeight.Text.Length
      End If
    End Sub

    Private Sub txtWeight_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtWeight.KeyPress
      If e.KeyChar = Chr(13) Then
            e.Handled = True
            Call CalWeight()
      Else
            '// รับค่าเฉพาะตัวเลขแบบจำนวนเต็ม
            'e.Handled = CheckDigitOnly(Asc(e.KeyChar))
            e.Handled = ValidateNumeric(e.KeyChar)
      End If
    End Sub

    ' / --------------------------------------------------------------------------------
    ' / S A M P L E ... D A T A    T A B L E (Products)
    ' / --------------------------------------------------------------------------------
    Function GetDataTable() As DataTable
      '// Add Column
      Dim DT As New DataTable
      With DT.Columns
            .Add("WeightPK", GetType(Integer)) '<< Index = 0
            .Add("WeightName", GetType(String)) '<< 1
            .Add("BeginWeight", GetType(Integer)) '<< 2
            .Add("EndWeight", GetType(Integer)) '<< 3
            .Add("PriceEnvelope", GetType(Double)) '<< 4
            .Add("PriceBox", GetType(Double)) '<< 5
            .Add("PriceEnvelopeBox", GetType(Double)) '<< 6
      End With
      '/ Add sample data.
      '/ WeightPK, WeightName, BeginWeight, EndWeight, PriceEnvelope, PriceBox, PriceEnvelopeBox
      With DT.Rows
            .Add(1, "ไม่เกิน 20 กรัม", "1", "20", "16.00", "18.00", "20.00")
            .Add(2, "เกิน 20 กรัม - 100 กรัม", "21", "100", "18.00", "20.00", "22.00")
            .Add(3, "เกิน 100 กรัม - 250 กรัม", "101", "250", "22.00", "24.00", "26.00")
            .Add(4, "เกิน 250 กรัม - 500 กรัม", "251", "500", "28.00", "30.00", "30.00")
            .Add(5, "เกิน 500 กรัม - 1,000 กรัม", "501", "1000", "38.00", "40.00", "40.00")
            .Add(6, "เกิน 1,000 กรัม - 2,000 กรัม", "1001", "2000", "58.00", "60.00", "60.00")
            .Add(7, "เกิน 2,000 กรัม - 4,000 กรัม", "2001", "4000", "0.00", "0.00", "80.00")
            .Add(8, "เกิน 4,000 กรัม - 6,000 กรัม", "4001", "6000", "0.00", "0.00", "120.00")
            .Add(9, "เกิน 6,000 กรัม - 10,000 กรัม", "6001", "10000", "0.00", "0.00", "160.00")
      End With
      Return DT
    End Function

    Private Sub CalWeight()
      If txtWeight.Text.Trim = "" Or txtWeight.Text.Trim.Length = 0 Then
            txtWeight.Text = "0"
            Return
      End If
      Dim DT As DataTable = GetDataTable()
      '/ ค้นหาข้อมูลจากน้ำหนักที่ต้องการ แล้วเปรียบเทียบช่วงค่าระหว่างน้ำหนักต่ำสุดและน้ำหนักสูงสุด
      Dim r() As DataRow = DT.Select(CInt(txtWeight.Text.Trim) & " >= BeginWeight AND " & CInt(txtWeight.Text.Trim) & "<= EndWeight")
      '// หากพบข้อมูลใน DataTable
      If r.Count > 0 Then
            txtWeight.Tag = r(0).Item(0).ToString
            txtPriceEnvelope.Text = Format(CDbl(r(0).Item(4).ToString), "0.00")
            txtPriceBox.Text = Format(CDbl(r(0).Item(5).ToString), "0.00")
            txtPriceEnvelopeBox.Text = Format(CDbl(r(0).Item(6).ToString), "0.00")
            txtWeightDescription.Text = r(0).Item(1).ToString
            '// กรณีที่อัตราค่าบริการซองและกล่อง = 0.00 ให้ไปโฟกัสที่ประเภทซองและกล่อง
            If Val(r(0).Item(4).ToString) = 0 AndAlso Val(r(0).Item(5).ToString) = 0 Then
                rdoEnvelopeBox.Focus()
            Else
                rdoEnvelope.Focus()
            End If
      Else
            Call ClearTextBox()
      End If
      DT.Dispose()
      txtWeight.Focus()
    End Sub

    Private Sub btnCalWeight_Click(sender As System.Object, e As System.EventArgs) Handles btnCalWeight.Click
      Call CalWeight()
      txtWeight.Focus()
    End Sub

    ' / --------------------------------------------------------------------------------
    ' / ตั้งค่าเริ่มต้นให้กับ DataGridView แบบ Run Time (ใช้โค้ดทั้งหมด)
    Private Sub InitializeGrid()
      With dgvData
            .RowHeadersVisible = False
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .AllowUserToResizeRows = False
            .MultiSelect = False
            .ReadOnly = True
            .RowTemplate.MinimumHeight = 30
            .RowTemplate.Height = 30
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            '/ Columns Specified
            '/ Index = 0
            .Columns.Add("PK", "Primary Key")
            With .Columns("PK")
                .DefaultCellStyle.BackColor = Color.LightGoldenrodYellow
                .Visible = False '/ ปกติหลัก Primary Key จะต้องถูกซ่อนไว้
            End With
            '/ Index = 1
            .Columns.Add("Category", "Category")
            .Columns("Category").DefaultCellStyle.BackColor = Color.LightGoldenrodYellow
            '/ Index = 2
            .Columns.Add("WeightDescription", "Weight Description")
            .Columns("WeightDescription").DefaultCellStyle.BackColor = Color.LightGoldenrodYellow
            '/ Index = 3
            .Columns.Add("Weight", "Weight")
            .Columns("Weight").ValueType = GetType(Integer)
            '/ Index = 4
            .Columns.Add("UnitPrice", "Unit Price")
            .Columns("UnitPrice").ValueType = GetType(Double)
      End With
      '// เพิ่มปุ่มลบ (Index = 5)
      Dim btnDelRow As New DataGridViewButtonColumn
      dgvData.Columns.Add(btnDelRow)
      With btnDelRow
            .HeaderText = "Delete F8"
            .Text = "Delete"
            .UseColumnTextForButtonValue = True
            .Width = 30
            .ReadOnly = True
            .HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
            .SortMode = DataGridViewColumnSortMode.NotSortable'/ Not sort order but can click header for delete row.
      End With
      '/ Alignment MiddleRight only columns 3 to 5
      For i As Byte = 3 To 4
            With dgvData
                '/ Header Alignment
                .Columns(i).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight
                '/ Cell Alignment
                .Columns(i).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .DefaultCellStyle.BackColor = Color.LightGoldenrodYellow
                .DefaultCellStyle.ForeColor = Color.Blue
                .DefaultCellStyle.Font = New Font(dgvData.Font, FontStyle.Bold)
            End With
      Next
      With dgvData
            '// Even-Odd Color
            .AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue
            '/ Auto size column width of each main by sorting the field.
            .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
            .AutoResizeColumns()
            '/ Adjust Header Styles
            With .ColumnHeadersDefaultCellStyle
                .BackColor = Color.Orange
                .ForeColor = Color.Black
                .Font = New Font("Tahoma", 11, FontStyle.Bold)
            End With
            .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
            .ColumnHeadersHeight = 40
            '/ กำหนดให้ EnableHeadersVisualStyles = False เพื่อให้ยอมรับการเปลี่ยนแปลงสีพื้นหลังของ Header
            .EnableHeadersVisualStyles = False
      End With
    End Sub

    Private Sub btnAddToDataGridView_Click(sender As System.Object, e As System.EventArgs) Handles btnAddToDataGridView.Click
      If txtWeight.Tag = 0 Then
            txtWeight.Focus()
            Exit Sub
      End If
      If (CInt(txtPriceEnvelope.Text) = 0 And CInt(txtPriceBox.Text) = 0) AndAlso (rdoEnvelope.Checked Or rdoBox.Checked) Then
            MessageBox.Show("ไม่สามารถเพิ่มรายการได้ เนื่องจากอยู่นอกเหนือจากพิกัดน้ำหนัก.", "รายงานสถานะ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Return
      End If
      Dim Category As String = String.Empty
      Dim Price As Double = "0.00"
      If rdoEnvelope.Checked Then
            Price = txtPriceEnvelope.Text
            Category = lblEnvelope.Text
      ElseIf rdoBox.Checked Then
            Price = txtPriceBox.Text
            Category = lblBox.Text
      Else
            Price = txtPriceEnvelopeBox.Text
            Category = lblEnvelopeBox.Text
      End If
      '/ Primary Key (Weight), Category (มาจาก Label), WeightDescription (มาจาก TextBox), Weight, Price
      dgvData.Rows.Add(txtWeight.Tag, Category, txtWeightDescription.Text, Format(CInt(txtWeight.Text), "#,##0"), Format(Price, "0.00"))
      txtWeight.Tag = 0
      Call ClearTextBox()
      txtWeight.Focus()
    End Sub

    ' / --------------------------------------------------------------------------------
    ' / โปรแกรมย่อยในการลบแถวรายการที่เลือกออกไป
    Private Sub DeleteRow(ByVal ColName As String)
      If dgvData.RowCount = 0 Then Return
      '/ ColName เป็นชื่อของหลัก Index = 6 ของตารางกริด (ไปดูที่โปรแกรมย่อย InitializeGrid)
      If ColName = "btnDelRow" Then
            '// ลบรายการแถวที่เลือกออกไป
            dgvData.Rows.Remove(dgvData.CurrentRow)
      End If
      txtWeight.Focus()
    End Sub

    Private Sub rdoEnvelope_Click(sender As Object, e As System.EventArgs) Handles rdoEnvelope.Click
      txtPriceEnvelope.BackColor = Color.Red
      txtPriceBox.BackColor = Color.Yellow
      txtPriceEnvelopeBox.BackColor = Color.Yellow
      Call CalWeight()
    End Sub

    Private Sub rdoBox_Click(sender As Object, e As System.EventArgs) Handles rdoBox.Click
      txtPriceEnvelope.BackColor = Color.Yellow
      txtPriceBox.BackColor = Color.Red
      txtPriceEnvelopeBox.BackColor = Color.Yellow
      Call CalWeight()
    End Sub

    Private Sub rdoEnvelopeBox_Click(sender As Object, e As System.EventArgs) Handles rdoEnvelopeBox.Click
      txtPriceEnvelope.BackColor = Color.Yellow
      txtPriceBox.BackColor = Color.Yellow
      txtPriceEnvelopeBox.BackColor = Color.Red
      Call CalWeight()
    End Sub

    Private Sub txtWeight_LostFocus(sender As Object, e As System.EventArgs) Handles txtWeight.LostFocus
      If txtWeight.Text.Trim = "" Or txtWeight.Text.Trim.Length = 0 Then txtWeight.Text = "0"
    End Sub

    Private Sub dgvData_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvData.CellClick
      Select Case e.ColumnIndex
            '// Delete Button
            Case 5
                'MsgBox(("Row : " + e.RowIndex.ToString & "Col : ") + e.ColumnIndex.ToString)
                Call DeleteRow("btnDelRow")
      End Select
    End Sub

    Private Sub frmWeightCalculation_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
      Me.Dispose()
      GC.SuppressFinalize(Me)
      Application.Exit()
    End Sub
End Class
โมดูล modFunction.vb ...
Module modFunction

    ' / --------------------------------------------------------------------------------
    ' / Get my project path
    ' / AppPath = C:\My Project\bin\debug
    ' / Replace "\bin\debug" with "\"
    ' / Return : C:\My Project\
    ' / --------------------------------------------------------------------------------
    ' / ฟังค์ชั่นในการกำหนดพาธให้กับโปรแกรม
    Function MyPath(ByVal AppPath As String) As String
      MyPath = AppPath.ToLower.Replace("\bin\debug", "\").Replace("\bin\release", "\").Replace("\bin\x86\debug", "\")
      '// If not found folder then put the \ (BackSlash) at the end.
      '/ Return Value
      If Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
    End Function

    ' / Function to test for Positive Integers with zero inclusive.
    Public Function ValidateNumeric(ByVal strNumber As ) As Boolean
      Dim Pattern As New Regex("[^0-9]")
      Return Pattern.IsMatch(strNumber)
    End Function

    ' / --------------------------------------------------------------------------------
    ' / ฟังค์ชั่นในการป้อนเฉพาะค่าตัวเลขได้เท่านั้น
    Function CheckDigitOnly(ByVal index As Integer) As Boolean
      Select Case index
            Case 48 To 57 ' เลข 0 - 9
                CheckDigitOnly = False
            Case 8, 13 ' Backspace = 8, Enter = 13
                CheckDigitOnly = False
            Case Else
                CheckDigitOnly = True
      End Select
    End Function

    ' / --------------------------------------------------------------------------------
    ' / ฟังค์ชั่นในการป้อนเฉพาะค่าตัวเลขและทศนิยมได้ตัวเดียวเท่านั้น
    Function CheckCurrency(index As Integer, tmpStr As String) As Boolean
      CheckCurrency = False
      Select Case index
            Case 48 To 57 ' เลข 0 - 9
                ' Allowed "."
            Case 46
                ' can present "." only one
                If InStr(tmpStr, ".") Then CheckCurrency = True

            Case 8, 13 ' Backspace = 8, Enter = 13
            Case Else
                CheckCurrency = True
      End Select
    End Function

End Module
ดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010) ได้ที่นี่ ...
หน้า: [1]
ดูในรูปแบบกติ: [VB.NET] โค้ดการคำนวณหาอัตราค่าบริการขนส่งไปรษณีย์ (eCo Post)