SlideShare a Scribd company logo
1
Imports System.Data.SqlClient
Public Class FrmSaleProduct
Private Sub tsbtnAdd_Click(sender As Object, e As EventArgs) Handles tsbtnAdd.Click
Dim conn As SqlConnection
conn = New SqlConnection("Data Source = ISIN; Database=DBSale; integrated security=true")
If conn.State = ConnectionState.Open Then conn.Close()
conn.Open()
Dim strSql As String
strSql = "SELECT TOP 1 BillID FROM tb_Sale ORDER BY BillID DESC"
Dim da As New SqlDataAdapter(strSql, conn)
Dim ds As New DataSet
da.Fill(ds, "Sale") 'นำค่ำ da ใส่ใน ds ชื่อ product555
If ds.Tables("Sale").Rows.Count = 0 Then
txtBillid.Text = DateTime.Now.ToString("yy-MM") + "-" + "0001"
Else
Dim oldBillID As String = ds.Tables("Sale").Rows(0).Item("BillID").ToString().Substring(6)
Dim newBillID As String = (Convert.ToInt32(oldBillID) + 1).ToString("0000")
txtBillid.Text = DateTime.Now.ToString("yy-MM") + "-" + newBillID
End If
2
conn.Close()
dtpSaleDate.Enabled = True
txtCustomerId.Enabled = True
btnSelectCustomer.Enabled = True
txtProductId.Enabled = True
btnSelectProduct.Enabled = True
txtAmount.Enabled = True
btnAddProductSale.Enabled = True
tsbtnSave.Enabled = True
tsbtnAdd.Enabled = False
End Sub
Private Sub btnSelectCustomer_Click(sender As Object, e As EventArgs) Handles btnSelectCustomer.Click
dgvSelectCustomer.Visible = True
Dim conn As SqlConnection
conn = New SqlConnection("Data Source = ISIN; Database=DBSale; integrated security=true")
If conn.State = ConnectionState.Open Then conn.Close()
conn.Open()
'If conn.State = ConnectionState.Open Then MessageBox.Show("Connection OK")
Dim strSql As String
strSql = "SELECT CustomerId, Name FROM tb_Customers"
Dim da As New SqlDataAdapter(strSql, conn)
Dim ds As New DataSet
da.Fill(ds, "Customers")
dgvSelectCustomer.DataSource = ds.Tables("Customers")
conn.Close()
dgvSelectCustomer.Columns(0).HeaderText = "รหัสลูกค้ำ"
dgvSelectCustomer.Columns(1).HeaderText = "ชื่อลูกค้ำ"
dgvSelectCustomer.Columns(0).Width = 100
dgvSelectCustomer.Columns(1).Width = 150
End Sub
Private Sub txtCustomerId_KeyUp(sender As Object, e As KeyEventArgs) Handles txtCustomerId.KeyUp
Dim conn As SqlConnection
conn = New SqlConnection("Data Source = ISIN; Database=DBSale; integrated security=true")
If conn.State = ConnectionState.Open Then conn.Close()
conn.Open()
3
Dim strSql As String = "SELECT CustomerId, Name FROM tb_Customers Where CustomerID = '" + txtCustomerId.Text + "'"
Dim da As New SqlDataAdapter(strSql, conn)
Dim ds As New DataSet
da.Fill(ds, "Customers") 'นำค่ำ da ใส่ใน ds ชื่อ product555
If ds.Tables("Customers").Rows.Count = 0 Then
txtName.Text = ""
Else
txtName.Text = ds.Tables("Customers").Rows(0).Item("Name").ToString()
End If
conn.Close()
End Sub
Private Sub dgvSelectCustomer_CellMouseUp(sender As Object, e As DataGridViewCellMouseEventArgs) Handles
dgvSelectCustomer.CellMouseUp
If e.RowIndex < 0 Then
Exit Sub
End If
txtCustomerId.Text = dgvSelectCustomer.Rows(e.RowIndex).Cells(0).Value.ToString()
txtName.Text = dgvSelectCustomer.Rows(e.RowIndex).Cells(1).Value.ToString()
dgvSelectCustomer.Visible = False
End Sub
Private Sub txtProductId_KeyUp(sender As Object, e As KeyEventArgs) Handles txtProductId.KeyUp
Dim conn As SqlConnection
conn = New SqlConnection("Data Source = ISIN; Database=DBSale; integrated security=true")
If conn.State = ConnectionState.Open Then conn.Close()
conn.Open()
Dim strSql As String = "SELECT * FROM tb_Products Where ProductID = '" + txtProductId.Text + "'"
Dim da As New SqlDataAdapter(strSql, conn)
Dim ds As New DataSet
da.Fill(ds, "Products") 'นำค่ำ da ใส่ใน ds ชื่อ product555
If ds.Tables("Products").Rows.Count = 0 Then
txtProductName.Text = ""
txtUnitsInstock.Text = ""
txtSalePrice.Text = ""
Else
txtProductName.Text = ds.Tables("Products").Rows(0).Item("ProductName").ToString()
txtUnitsInstock.Text = ds.Tables("Products").Rows(0).Item("UnitsInstock").ToString()
txtSalePrice.Text = ds.Tables("Products").Rows(0).Item("SalePrice").ToString()
End If
conn.Close()
End Sub
Private Sub btnSelectProduct_Click(sender As Object, e As EventArgs) Handles btnSelectProduct.Click
4
dgvSelectProduct.Visible = True
Dim conn As SqlConnection
conn = New SqlConnection("Data Source = ISIN; Database=DBSale; integrated security=true")
If conn.State = ConnectionState.Open Then conn.Close()
conn.Open()
'If conn.State = ConnectionState.Open Then MessageBox.Show("Connection OK")
Dim strSql As String = "SELECT ProductID, ProductName, UnitsInstock, SalePrice FROM tb_Products"
Dim da As New SqlDataAdapter(strSql, conn)
Dim ds As New DataSet
da.Fill(ds, "Products")
dgvSelectProduct.DataSource = ds.Tables("Products")
conn.Close()
dgvSelectProduct.Columns(0).HeaderText = "รหัสสินค้ำ"
dgvSelectProduct.Columns(1).HeaderText = "ชื่อสินค้ำ"
dgvSelectProduct.Columns(2).HeaderText = "จำนวนในสต็อก"
dgvSelectProduct.Columns(3).HeaderText = "รำคำขำย"
dgvSelectProduct.Columns(0).Width = 100
dgvSelectProduct.Columns(1).Width = 150
dgvSelectProduct.Columns(2).Width = 120
dgvSelectProduct.Columns(3).Width = 100
End Sub
Private Sub dgvSelectProduct_CellMouseUp(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvSelectProduct.CellMouseUp
If e.RowIndex < 0 Then
Exit Sub
End If
txtProductId.Text = dgvSelectProduct.Rows(e.RowIndex).Cells(0).Value.ToString()
txtProductName.Text = dgvSelectProduct.Rows(e.RowIndex).Cells(1).Value.ToString()
txtUnitsInstock.Text = dgvSelectProduct.Rows(e.RowIndex).Cells(2).Value.ToString()
txtSalePrice.Text = dgvSelectProduct.Rows(e.RowIndex).Cells(3).Value.ToString()
dgvSelectProduct.Visible = False
End Sub
Private Sub btnAddProductSale_Click(sender As Object, e As EventArgs) Handles btnAddProductSale.Click
If txtProductName.Text = "" Then
MessageBox.Show("เลือกสินค้ำ")
ElseIf txtAmount.Text = "" Then
MessageBox.Show("กรุณำกรอกจำนวนที่ซื้อ")
ElseIf Convert.ToInt32(txtAmount.Text) > Convert.ToInt32(txtUnitsInstock.Text) Then
MessageBox.Show("จำนวนที่ซื้อมำกกว่ำ สินค้ำในสต็อก")
Else
Dim dgvRow As Integer = dgvSaleDetail.Rows.Count
5
If dgvRow <> 0 Then
For i As Integer = 0 To dgvRow - 1
If dgvSaleDetail.Rows(i).Cells(0).Value.ToString() = txtProductId.Text Then
Dim quantity As Integer = Convert.ToInt32(txtAmount.Text) + Convert.ToInt32(dgvSaleDetail.Rows(i).Cells(3).Value)
If quantity > Convert.ToInt32(txtUnitsInstock.Text) Then
MessageBox.Show("จำนวนที่ซื้อมำกกว่ำ สินค้ำในสต็อก")
Else
dgvSaleDetail.Rows(i).Cells(3).Value = quantity
Dim saleUpdate As Double = quantity * Convert.ToDouble(txtSalePrice.Text)
dgvSaleDetail.Rows(i).Cells(4).Value = saleUpdate
Dim saleTotalUpdate = Convert.ToDouble(lblTotal.Text) + (Convert.ToInt32(txtAmount.Text) *
Convert.ToDouble(txtSalePrice.Text))
lblTotal.Text = saleTotalUpdate.ToString("#,##0.00")
End If
txtProductId.Clear()
txtUnitsInstock.Clear()
txtProductName.Clear()
txtSalePrice.Clear()
txtAmount.Clear()
Exit Sub
End If
Next
End If
Dim numRow = dgvSaleDetail.Rows.Add()
dgvSaleDetail.Rows(numRow).Cells(0).Value = txtProductId.Text
dgvSaleDetail.Rows(numRow).Cells(1).Value = txtProductName.Text
dgvSaleDetail.Rows(numRow).Cells(2).Value = txtSalePrice.Text
dgvSaleDetail.Rows(numRow).Cells(3).Value = txtAmount.Text
Dim salePrice As Double = Convert.ToInt32(txtAmount.Text) * Convert.ToDouble(txtSalePrice.Text)
dgvSaleDetail.Rows(numRow).Cells(4).Value = salePrice
Dim saleTotal As Double = Convert.ToDouble(lblTotal.Text) + salePrice
lblTotal.Text = saleTotal.ToString("#,##0.00")
txtProductId.Clear()
txtUnitsInstock.Clear()
txtProductName.Clear()
txtSalePrice.Clear()
txtAmount.Clear()
End If
End Sub
Private Sub dgvSaleDetail_CellMouseDoubleClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles
dgvSaleDetail.CellMouseDoubleClick
Dim rowSelect As Integer = e.RowIndex
6
Dim total As Double = Convert.ToDouble(lblTotal.Text) - Convert.ToDouble(dgvSaleDetail.Rows(rowSelect).Cells(4).Value.ToString())
lblTotal.Text = total.ToString("#,##0.00")
dgvSaleDetail.Rows.RemoveAt(rowSelect)
End Sub
Private Sub tsbtnSave_Click(sender As Object, e As EventArgs) Handles tsbtnSave.Click
If txtName.Text = "" Then
MessageBox.Show("เลือกชื่อลูกค้ำด้วย")
ElseIf dgvSaleDetail.Rows.Count = 0 Then
MessageBox.Show("เลือกสินค้ำที่จะซื้อด้วย")
Else
Dim conn As SqlConnection
conn = New SqlConnection("Data Source = ISIN; Database=DBSale; integrated security=true")
If conn.State = ConnectionState.Open Then conn.Close()
conn.Open()
'If conn.State = ConnectionState.Open Then MessageBox.Show("Connection OK")
Dim cm As New SqlCommand
cm.Connection = conn
cm.CommandType = CommandType.Text
Dim strSql As String
strSql = "insert into tb_sale (billId, saleDate, customerId, total) values ('" + txtBillid.Text + "', '" +
dtpSaleDate.Value.Date.ToString("yyyy-MM-dd", New System.Globalization.CultureInfo("en-US")) + "', '" + txtCustomerId.Text + "', " +
lblTotal.Text + ")"
cm.CommandText = strSql
cm.ExecuteNonQuery()
MessageBox.Show("บันทึกเรียบร้อยแล้ว")
conn.Close()
End If
End Sub
End Class
Save File Dialog Confirm
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
SaveFileDialog1.DefaultExt = "*.rtf"
SaveFileDialog1.Filter = "RTF Files|*.rtf"
7
SaveFileDialog1.CreatePrompt = True
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
RichTextBox1.SaveFile(SaveFileDialog1.FileName, RichTextBoxStreamType.RichText)
End If
End Sub
มินิโปรเจค
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms
8
Namespace WindowsFormsApplication1
Public Partial Class AddOrder
Inherits Form
Private btnText As String
Public Sub New(btnText As String)
InitializeComponent()
Me.btnText = btnText
End Sub
Private Sub loadDataToAdd()
Dim nt As Integer = Convert.ToInt16(btnText.Substring(7))
'sub x
Dim T00 As String = "T" + nt.ToString("00")
'1.ติดต่อฐำนข้อมูล
'string conStr = "server=Localhost;initial catalog=DBBarBQ;integrated security=true";
Dim conStr As String = "server=Localhost ;initial catalog=DBBarBQ;integrated security=true"
Dim connectDB As New SqlConnection(conStr)
If connectDB.State = ConnectionState.Open Then
connectDB.Close()
End If
Try
'MessageBox.Show("โอเคผ่ำน");
connectDB.Open()
Catch ex As Exception
MessageBox.Show("can't Database open." + ex.Message)
Return
End Try
'2.คำสั่ง SQL BillID,TableID,SaleDate,AmountChild,AmountAdult,Total,Fined,AmountFined,Status
'tb_xxxx1 a left join tb_xxxx2 b on a.BillID=b.BillID
9
Dim strSql As String = (Convert.ToString("select * " + " from tb_Sale S left join tb_saledetail SD on S.BillID=SD.BillID" +
" where S.status = 'Yes' and S.TableID = '") & T00) + "'"
'สมมติ T01 มี ทำ ถ้ำไม่มี ไม่ทำ
'3.สั่งให้ SQl ทำงำน
Dim cmd As New SqlCommand(strSql, connectDB)
'ทำงำน
Dim dr As SqlDataReader = cmd.ExecuteReader()
'สั่งให้ทำงำน + ดึงค่ำที่ได้มำ
'3.1 ทำอะไรก็แล้วแต่
If dr.Read() Then
txtBill.Text = dr("BillID").ToString()
txtChild.Text = dr("AmountChild").ToString()
txtAdult.Text = dr("AmountAdult").ToString()
txtAmount.Text = dr("AmountFined").ToString()
End If
'4.
connectDB.Close()
'###################################### dgvBev #######################################//
If connectDB.State = ConnectionState.Closed Then
connectDB.Open()
End If
If True Then
'1.ติดต่อฐำนข้อมูล
'string conStr = "server=Localhost;initial catalog=DBBarBQ;integrated security=true";
'string conStr2 = "server=Localhost ;initial catalog=DBBarBQ;integrated security=true";
'SqlConnection connectDB2 = new SqlConnection(conStr2);
If connectDB.State = ConnectionState.Open Then
connectDB.Close()
End If
10
Try
'MessageBox.Show("โอเคผ่ำน");
connectDB.Open()
Catch ex As Exception
MessageBox.Show("can't Database open." + ex.Message)
Return
End Try
'2.คำสั่ง SQL BillID,TableID,SaleDate,AmountChild,AmountAdult,Total,Fined,AmountFined,Status
'2.คำสั่ง SQL BeveragesID ,BeveragesName ,SalePrice ,Cost ,UnitStock
Dim strSqlBev As String = "select BeveragesID, BeveragesName , SalePrice , UnitStock from tb_Beverages"
'คำสั่ง
'3.สั่งให้ SQl ทำงำน
Dim cmd2 As New SqlCommand(strSqlBev, connectDB)
'ทำงำน
Dim dr2 As SqlDataReader = cmd2.ExecuteReader()
'สั่งให้ทำงำน + ดึงค่ำที่ได้มำ
'3.1 ทำอะไรก็แล้วแต่ เอำไปใส่ใน DataGridview Bevproduct
'connectDB.Close();
While dr2.Read()
'กรณีมีข้อมูล
'MessageBox.Show(dr2["BeveragesID"].ToString());
'เพิ่มแถวใน GV พร้อมกับกำหนดตัวแปร เก็บหมำยเลขแถว
Dim numRow As Integer = dgvBev.Rows.Add()
'numRow = numRow;
'3.1 product
dgvBev.Rows(numRow).Cells(0).Value = dr2("BeveragesID").ToString()
dgvBev.Rows(numRow).Cells(1).Value = dr2("BeveragesName").ToString()
dgvBev.Rows(numRow).Cells(2).Value = dr2("UnitStock").ToString()
dgvBev.Rows(numRow).Cells(3).Value = dr2("SalePrice").ToString()
'txtProductId.Text = dr2["BeveragesID"].ToString();
11
numRow = numRow + 1
End While
'DataTable dt2 = new DataTable();
'dt2.Load(dr2);//เก็บสิ่งที่ได้มำ
'dgvAddBev.DataSource = dt2;//เอำสิ่งที่เก็บใส่ DataGridView
connectDB.Close()
End If
'###################################### dgvAddBev #######################################//
If connectDB.State = ConnectionState.Closed Then
connectDB.Open()
End If
If True Then
'MessageBox.Show("Op1");
'1.ติดต่อฐำนข้อมูล
'string conStr = "server=Localhost;initial catalog=DBBarBQ;integrated security=true";
'string conStr2 = "server=Localhost ;initial catalog=DBBarBQ;integrated security=true";
'SqlConnection connectDB2 = new SqlConnection(conStr2);
'if (connectDB.State == ConnectionState.Closed) connectDB.Open();
If connectDB.State = ConnectionState.Open Then
connectDB.Close()
End If
Try
'MessageBox.Show("โอเคผ่ำน");
connectDB.Open()
Catch ex As Exception
MessageBox.Show("can't Database open." + ex.Message)
12
Return
End Try
'2.คำสั่ง SQL BillID,TableID,SaleDate,AmountChild,AmountAdult,Total,Fined,AmountFined,Status
'2.คำสั่ง SQL BeveragesID ,BeveragesName ,SalePrice ,Cost ,UnitStock
Dim strSqlAddBev As String = (Convert.ToString("select * " + " from tb_SaleDetail SD left join tb_Beverages
Bev on SD.BeveragesID=Bev.BeveragesID " + " left join tb_Sale S on SD.BillID=S.BillID " + " where
SD.BeveragesID=Bev.BeveragesID " + " and S.status = 'Yes' and S.TableID = '") & T00) + "'"
'3.สั่งให้ SQl ทำงำน
Dim cmd3 As New SqlCommand(strSqlAddBev, connectDB)
'ทำงำน
Dim dr3 As SqlDataReader = cmd3.ExecuteReader()
'สั่งให้ทำงำน + ดึงค่ำที่ได้มำ
'3.1 ทำอะไรก็แล้วแต่ เอำไปใส่ใน DataGridview Bevproduct
While dr3.Read()
'กรณีมีข้อมูล
'MessageBox.Show(dr3["BeveragesID"].ToString()+"Before");
'เพิ่มแถวใน GV พร้อมกับกำหนดตัวแปร เก็บหมำยเลขแถว
Dim numRow As Integer = dgvAddBev.Rows.Add()
'numRow = numRow;
'3.1 product
dgvAddBev.Rows(numRow).Cells(0).Value = dr3("BeveragesID").ToString()
dgvAddBev.Rows(numRow).Cells(1).Value = dr3("BeveragesName").ToString()
dgvAddBev.Rows(numRow).Cells(2).Value = dr3("UnitStock").ToString()
dgvAddBev.Rows(numRow).Cells(3).Value = dr3("SalePrice").ToString()
'txtProductId.Text = dr2["BeveragesID"].ToString();
numRow = numRow + 1
End While
'
13
' DataTable dt = new DataTable();
' dt.Load(dr3);//เก็บสิ่งที่ได้มำ
' int dtnum = dt.Rows.Count;
' MessageBox.Show(dtnum.ToString());
' if (dtnum > 0)
' {
' dataGridView1.Enabled = true;
' dataGridView1.Visible = true;
' }
' else
' {
' dataGridView1.Enabled = false;
' dataGridView1.Visible = false;
' }
' dataGridView1.DataSource = dt;//เอำสิ่งที่เก็บใส่ DataGridView
' dataGridView1.Columns[0].Width = 100;
' dataGridView1.Columns[1].Width = 250;
' dataGridView1.Columns[2].Width = 150;
' dataGridView1.Columns[3].Width = 150;
' dataGridView1.Columns[4].Width = 150;
'
connectDB.Close()
End If
End Sub
Private Sub AddOrder_Load(sender As Object, e As EventArgs)
lblTableX.Text = btnText
'โตะที่ x
14
loadDataToAdd()
End Sub
Private Sub dgvBev_CellMouseUp(sender As Object, e As DataGridViewCellMouseEventArgs)
If e.RowIndex = -1 Then
Return
End If
txtBevID.Text = dgvBev.Rows(e.RowIndex).Cells(0).Value.ToString()
txtBevName.Text = dgvBev.Rows(e.RowIndex).Cells(1).Value.ToString()
txtAmount.Enabled = True
txtAmount.Focus()
btnAddProductSale.Enabled = True
btnDelete.Enabled = True
End Sub
Private Sub tsbtnHome_Click(sender As Object, e As EventArgs)
AddOrder.ActiveForm.Close()
End Sub
Private Sub chkChild_CheckedChanged(sender As Object, e As EventArgs)
15
If chkChild.Checked Then
txtChild.Enabled = True
txtChild.Focus()
Else
txtChild.Enabled = False
txtChild.Focus()
End If
End Sub
Private Sub chkAdult_CheckedChanged(sender As Object, e As EventArgs)
If chkAdult.Checked Then
txtAdult.Enabled = True
txtAdult.Focus()
Else
txtAdult.Enabled = False
txtAdult.Focus()
End If
End Sub
Private Sub txtChild_KeyPress(sender As Object, e As KeyPressEventArgs)
End Sub
Private Sub txtAdult_KeyPress(sender As Object, e As KeyPressEventArgs)
End Sub
Private Sub btnAddProductSale_Click(sender As Object, e As EventArgs)
End Sub
16
Private Sub tsbtnHome_Click_1(sender As Object, e As EventArgs)
Dim ManageBv As New ManageBv()
Me.Close()
ManageBv.Show()
End Sub
Private Sub tsbtnManageBv_Click(sender As Object, e As EventArgs)
Dim ManageBv As New ManageBv()
Me.Close()
ManageBv.Show()
End Sub
Private Sub tsbtnPricePeople_Click(sender As Object, e As EventArgs)
Dim PricePeople As New PricePeople()
Me.Close()
PricePeople.Show()
End Sub
Private Sub tsbtnReportEarn_Click(sender As Object, e As EventArgs)
Dim ReportEarn As New ReportEarn()
Me.Close()
ReportEarn.Show()
End Sub
Private Sub btnSaveOrder_Click(sender As Object, e As EventArgs)
End Sub
Private Sub btnCancelOrder_Click(sender As Object, e As EventArgs)
17
End Sub
' private void txtChild_TextChanged(object sender, EventArgs e)
' {
' int number;
' if (!Int32.TryParse(txtChild.Text, out number))
' {
' MessageBox.Show("ข้อมูลของคุณต้องเป็นตัวเลขจำนวนเต็มเท่ำนั้น", "ตรวจสอบตัวเลข", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
' }
' }
Private Sub txtChild_KeyPress_1(sender As Object, e As KeyPressEventArgs)
If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) AndAlso (e.KeyChar <> "."C) Then
e.Handled = True
End If
' only allow one decimal point
If (e.KeyChar = "."C) AndAlso (TryCast(sender, TextBox).Text.IndexOf("."C) > -1) Then
e.Handled = True
End If
End Sub
Private Sub chkFined_CheckedChanged(sender As Object, e As EventArgs)
If chkFined.Checked Then
txtAmountFined.Enabled = True
txtAmountFined.Focus()
Else
txtAmountFined.Enabled = False
txtAmountFined.Focus()
End If
18
End Sub
Private Sub txtChild_KeyPress_2(sender As Object, e As KeyPressEventArgs)
If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) AndAlso (e.KeyChar <> "."C) Then
e.Handled = True
End If
' only allow one decimal point
If (e.KeyChar = "."C) AndAlso (TryCast(sender, TextBox).Text.IndexOf("."C) > -1) Then
e.Handled = True
End If
End Sub
Private Sub dgvBev_CellContentClick(sender As Object, e As DataGridViewCellEventArgs)
End Sub
End Class
End Namespace
Manage BV
Imports System.Data.SqlClient
Public Class ManagBv
Dim flag As String
Private Sub ToolStripButton3_Click(sender As Object, e As EventArgs)
Me.Hide()
Main.Show()
End Sub
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs)
Me.Hide()
'addOrder.Show()
End Sub
Private Sub ManagBv_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If True Then
19
'1.ติดต่อฐำนข้อมูล
'string conStr = "server=ASUS-PCSqlExpress;initial catalog=DBBarBQ;integrated security=true";
Dim conStr As String = "server=ISIN;initial catalog=DBBarBQ;integrated security=true"
Dim connectDB As New SqlConnection(conStr)
If connectDB.State = ConnectionState.Open Then
connectDB.Close()
End If
Try
'MessageBox.Show("โอเคผ่ำน");
connectDB.Open()
Catch ex As Exception
MessageBox.Show("can't Database open." + ex.Message)
Return
End Try
'2.คำสั่ง SQL BeveragesID , BeveragesName , SalePrice , Cost , UnitStock
Dim strSql As String = "select BeveragesID, BeveragesName , Cost , SalePrice , UnitStock from tb_Beverages"
'คำสั่ง
'3.สั่งให้ SQl ทำงำน
Dim cmd As New SqlCommand(strSql, connectDB)
'ทำงำน
Dim dr As SqlDataReader = cmd.ExecuteReader()
'สั่งให้ทำงำน + ดึงค่ำที่ได้มำ
'3.1 ทำอะไรก็แล้วแต่
Dim dt As New DataTable()
dt.Load(dr)
'เก็บสิ่งที่ได้มำ
dgvEditProduct.DataSource = dt
'เอำสิ่งที่เก็บใส่ DataGridView
connectDB.Close()
dgvEditProduct.Columns(0).HeaderText = "เลขที่สินค้ำ"
'กำหนดชื่อหัวColum
dgvEditProduct.Columns(1).HeaderText = "ชื่อเครื่องดื่ม"
dgvEditProduct.Columns(2).HeaderText = "รำคำทุน"
dgvEditProduct.Columns(3).HeaderText = "รำคำขำย"
dgvEditProduct.Columns(4).HeaderText = "จำนวนในสต็อก"
dgvEditProduct.Columns(0).Width = 100
dgvEditProduct.Columns(1).Width = 200
dgvEditProduct.Columns(2).Width = 100
dgvEditProduct.Columns(3).Width = 100
dgvEditProduct.Columns(4).Width = 120
End If
End Sub
Private Sub btnCancle_Click(sender As Object, e As EventArgs) Handles btnCancle.Click
If True Then
btnAdd.Enabled = True
btnCancle.Enabled = False
btnSave.Enabled = False
20
btnEdit.Enabled = False
btnDelete.Enabled = False
txtEditProductName.Enabled = False
txtEditStock.Enabled = False
txtEditCost.Enabled = False
txtEditPrice.Enabled = False
txtEditSearch.Focus()
txtEditProductId.Clear()
txtEditProductName.Text = "กรอกรำยละเอียด"
txtEditStock.Text = "กรอกรำยละเอียด"
txtEditCost.Text = "กรอกรำยละเอียด"
txtEditPrice.Text = "กรอกรำยละเอียด"
txtEditSearch.Text = "กรอกรำยละเอียด"
loadDateToDgvEditProducts()
End If
End Sub
Private Sub dgvEditProduct_CellMouseUp(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvEditProduct.CellMouseUp
If True Then
If e.RowIndex = -1 Then
Return
End If
txtEditProductId.Text = dgvEditProduct.Rows(e.RowIndex).Cells("BeveragesID").Value.ToString()
txtEditProductName.Text = dgvEditProduct.Rows(e.RowIndex).Cells("BeveragesName").Value.ToString()
txtEditStock.Text = dgvEditProduct.Rows(e.RowIndex).Cells("UnitStock").Value.ToString()
txtEditCost.Text = dgvEditProduct.Rows(e.RowIndex).Cells("Cost").Value.ToString()
txtEditPrice.Text = dgvEditProduct.Rows(e.RowIndex).Cells("SalePrice").Value.ToString()
txtEditStock.Focus()
btnAdd.Enabled = False
btnCancle.Enabled = True
btnEdit.Enabled = True
btnDelete.Enabled = True
End If
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
If True Then
flag = "Add"
txtEditStock.Clear()
txtEditPrice.Clear()
txtEditProductName.Clear()
txtEditProductId.Clear()
txtEditCost.Clear()
21
btnAdd.Enabled = False
btnCancle.Enabled = True
btnSave.Enabled = True
txtEditProductName.Enabled = True
txtEditProductName.Focus()
txtEditStock.Enabled = True
txtEditCost.Enabled = True
txtEditPrice.Enabled = True
'1.ติดต่อฐำนข้อมูล
Dim conStr As String = "server=ISIN;initial catalog=DBBarBQ;integrated security=true"
Dim connectDB As New SqlConnection(conStr)
If connectDB.State = ConnectionState.Open Then
connectDB.Close()
End If
Try
'MessageBox.Show("โอเคผ่ำน");
connectDB.Open()
Catch ex As Exception
MessageBox.Show("can't Database open." + ex.Message)
Return
End Try
'2.คำสั่ง SQL
Dim strSql As String = "select top 1 BeveragesID from tb_Beverages order by BeveragesID DESC"
'3.สั่งให้ SQl ทำงำน
Dim cmd As New SqlCommand(strSql, connectDB)
Dim dr As SqlDataReader = cmd.ExecuteReader()
'3.1 ทำอะไรก็แล้วแต่
If dr.Read() Then
'กรณีที่มีรหัสอยู่แล้ว
Dim oldwaID As String = dr("BeveragesID").ToString()
Dim newWaId As Integer = Convert.ToInt16(oldwaID.Substring(3)) + 1
'oldwaID เอำมำsub
txtEditProductId.Text = "wa" + newWaId.ToString("000")
Else
'กรณีที่ไม่มีรหัสสินค้ำเครื่องดื่ม
txtEditProductId.Text = "wa001"
End If
'4.ยกเลิกติดต่อ
connectDB.Close()
End If
End Sub
22
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
If txtEditProductName.Text = "" Then
MessageBox.Show("กรุณำกรอกชื่อสินค้ำ/เครื่องดื่ม")
ElseIf txtEditStock.Text = "" Then
MessageBox.Show("กรุณำกรอกจำนวนสต๊อก")
ElseIf txtEditCost.Text = "" Then
MessageBox.Show("กรุณำกรอกรำคำทุน")
ElseIf txtEditPrice.Text = "" Then
MessageBox.Show("กรุณำกรอกรำคำขำย")
ElseIf flag = "Add" Then
'MessageBox.Show("add");
'1.ติดต่อฐำนข้อมูล
Dim conStr As String = "server=ISIN;initial catalog=DBBarBQ;integrated security=true"
Dim connectDB As New SqlConnection(conStr)
If connectDB.State = ConnectionState.Open Then
connectDB.Close()
End If
Try
'MessageBox.Show("โอเคผ่ำน");
connectDB.Open()
Catch ex As Exception
MessageBox.Show("can't Database open." + ex.Message)
Return
End Try
'2. Sql statement BeveragesID, BeveragesName , Cost , SalePrice , UnitStock
Dim strSql As [String] = "Insert into tb_Beverages (BeveragesID,BeveragesName,Cost,SalePrice,UnitStock)values(" + "'" +
txtEditProductId.Text + "'" + ",'" + txtEditProductName.Text + "'" + ",'" + txtEditStock.Text + "'" + ",'" + txtEditCost.Text + "'" + ",'" +
txtEditPrice.Text + "'" + ")"
'3. สั่ง Sql statement ทำงำน
Dim cmd As New SqlCommand(strSql, connectDB)
cmd.ExecuteNonQuery()
'3.1 ทำอะไรก็แล้วแต่
MessageBox.Show("บันทึกหน้ำจอเรียบร้อยแล้ว")
'4. Disconnect
connectDB.Close()
btnCancle.PerformClick()
End If
End Sub
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
flag = "update"
btnEdit.Enabled = False
btnDelete.Enabled = False
btnSave.Enabled = True
txtEditProductName.Enabled = True
txtEditProductName.Focus()
23
txtEditStock.Enabled = True
txtEditCost.Enabled = True
txtEditPrice.Enabled = True
End Sub
Private Sub loadDateToDgvEditProducts()
End Sub
Private Sub ToolStripButton1_Click_1(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
Me.Hide()
Main.Show()
End Sub
Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click
Me.Hide()
End Sub
Private Sub ToolStripButton4_Click(sender As Object, e As EventArgs) Handles ToolStripButton4.Click
Me.Hide()
PricePeople.Show()
End Sub
Private Sub ToolStripButton5_Click_1(sender As Object, e As EventArgs) Handles ToolStripButton5.Click
Me.Hide()
ReportEarn.Show()
End Sub
Private Sub txtEditStock_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtEditStock.KeyPress
If e.KeyChar.ToString = "." And txtEditStock.Text.Contains(".") Then
e.Handled = True
Exit Sub
End If
Dim regex As String = "^[0-9.rntbs]+$"
Dim r As New System.Text.RegularExpressions.Regex(regex)
If r.IsMatch(e.KeyChar.ToString()) Then
e.Handled = False
Else
e.Handled = True
End If
End Sub
Private Sub txtEditCost_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtEditCost.KeyPress
If e.KeyChar.ToString = "." And txtEditCost.Text.Contains(".") Then
e.Handled = True
Exit Sub
End If
24
Dim regex As String = "^[0-9.rntbs]+$"
Dim r As New System.Text.RegularExpressions.Regex(regex)
If r.IsMatch(e.KeyChar.ToString()) Then
e.Handled = False
Else
e.Handled = True
End If
End Sub
Private Sub txtEditPrice_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtEditPrice.KeyPress
If e.KeyChar.ToString = "." And txtEditPrice.Text.Contains(".") Then
e.Handled = True
Exit Sub
End If
Dim regex As String = "^[0-9.rntbs]+$"
Dim r As New System.Text.RegularExpressions.Regex(regex)
If r.IsMatch(e.KeyChar.ToString()) Then
e.Handled = False
Else
e.Handled = True
End If
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
MessageBox.Show("ยืนยันกำรลบ")
btnDelete.Enabled = False
btnCancle.Enabled = True
If MessageBox.Show("ต้องกำรลบหรือไม่", "ยืนยัน", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
'1.ติดต่อฐำนข้อมูล
'string conStr = "server=ASUS-PCSqlExpress;initial catalog=DBBarBQ;integrated security=true";
Dim conStr As String = "server=ISIN;initial catalog=DBBarBQ;integrated security=true"
Dim connectDB As New SqlConnection(conStr)
If connectDB.State = ConnectionState.Open Then
connectDB.Close()
End If
Try
'MessageBox.Show("โอเคผ่ำน");
connectDB.Open()
Catch ex As Exception
MessageBox.Show("can't Database open." + ex.Message)
Return
End Try
Dim strSql As String = "delete from tb_Beverages where BeveragesID = '" + txtEditProductId.Text + "'"
Dim cmd As New SqlCommand(strSql, connectDB)
Dim dr As SqlDataReader = cmd.ExecuteReader()
25
MessageBox.Show("ลบรำยกำรเรียบร้อยแล้ว")
'4. Disconnect
connectDB.Close()
btnDelete.Enabled = False
btnCancle.Enabled = True
btnDelete.Enabled = False
btnCancle.Enabled = True
dgvEditProduct.Refresh()
End If
End Sub
End Class
Public Class PricePeople
Private Sub btnEdit_Click(sender As Object, e As EventArgs)
txtAdult.Enabled = True
End Sub
Private Sub btnEdit2_Click(sender As Object, e As EventArgs)
txtChild.Enabled = True
End Sub
Private Sub loadDataToPricePeople()
'1.ติดต่อฐานข้อมูล
Dim conStr As String = "server=Localhost;initial catalog=DBBarBQ;integrated security=true"
Dim connectDB As New SqlConnection(conStr)
If connectDB.State = ConnectionState.Open Then
connectDB.Close()
End If
Try
'MessageBox.Show("โอเคผ่าน");
connectDB.Open()
Catch ex As Exception
MessageBox.Show("can't Database open." + ex.Message)
Return
End Try
'2.คาสั่ง SQL (DateEdit,Child,Adult)
Dim strSql As String = "select top 1 Child, Adult , DateEdit from tb_PricePerson order by
DateEdit desc"
'คาสั่ง
'3.สั่งให้ SQl ทางาน
Dim cmd As New SqlCommand(strSql, connectDB)
'ทางาน
Dim dr As SqlDataReader = cmd.ExecuteReader()
'สั่งให้ทางาน + ดึงค่าที่ได้มา
'3.1 ทาอะไรก็แล้วแต่
If dr.Read() Then
txtAdult.Text = dr("Child").ToString()
txtChild.Text = dr("Adult").ToString()
26
Dim dateDr As String = dr("DateEdit").ToString()
dateDr = dateDr.Substring(0, 9)
'lblDateNowPrice.Text = DateTime.Now.ToString("dd MMMM yyyy", New
System.Globalization.CultureInfo("th-TH"))
End If
'4.ปิด
connectDB.Close()
txtChild.Enabled = False
txtAdult.Enabled = False
dtpEdit.Enabled = False
End Sub
Private Sub PricePeople_Load(sender As Object, e As EventArgs) Handles MyBase.Load
loadDataToPricePeople()
txtAdult.Enabled = False
txtChild.Enabled = False
End Sub
Private Sub btnEditDateFinish_Click(sender As Object, e As EventArgs)
dtpEdit.Enabled = True
End Sub
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles
ToolStripButton1.Click
Me.Hide()
Main.Show()
End Sub
Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles
ToolStripButton2.Click
Me.Hide()
AddOrder.Show()
End Sub
Private Sub ToolStripButton3_Click(sender As Object, e As EventArgs) Handles
ToolStripButton3.Click
Me.Hide()
ManagBv.Show()
End Sub
Private Sub ToolStripButton5_Click(sender As Object, e As EventArgs) Handles
ToolStripButton5.Click
Me.Hide()
ReportEarn.Show()
End Sub
Private Sub btnSavePricePeople_Click(sender As Object, e As EventArgs) Handles
btnSavePricePeople.Click
'MessageBox.Show(txtAdult.Text);
If Convert.ToInt16(txtAdult.Text) > 999 Then
MessageBox.Show("กรุณาระบุค่าบุฟเฟ่ต์ไม่เกิน 999 บาท")
txtAdult.Focus()
ElseIf Convert.ToInt16(txtChild.Text) > 999 Then
MessageBox.Show("กรุณาระบุค่าบุฟเฟ่ต์ไม่เกิน 999 บาท")
27
txtChild.Focus()
Else
'1.ติดต่อฐานข้อมูล
'string conStr = "server=ASUS-PCSqlExpress;initial catalog=DBBarBQ;integrated
security=true";
Dim conStr As String = "server=Localhost;initial catalog=DBBarBQ;integrated
security=true"
Dim connectDB As New SqlConnection(conStr)
If connectDB.State = ConnectionState.Open Then
connectDB.Close()
End If
Try
'MessageBox.Show("โอเคผ่าน");
connectDB.Open()
Catch ex As Exception
MessageBox.Show("can't Database open." + ex.Message)
Return
End Try
'String dateS = dtpFinish.Value.Date.ToShortDateString();
Dim dateEdit As String = DateTime.Now.ToString("yyyy-MM-dd " + "hh:mm:ss.fff")
Dim YYYYF As String = (Convert.ToInt16(dtpEdit.Value.[Date].ToString("yyyy")) -
543).ToString("0000")
'String dateF = dtpEdit.Value.Date.ToString(YYYYF + "-MM-dd " + "hh:mm:ss.fff");
Dim yyyy As Integer = Convert.ToInt16(dtpEdit.Value.[Date].ToString("yyyy"))
Dim MM As Integer = Convert.ToInt16(dtpEdit.Value.[Date].ToString("MM"))
Dim dd As Integer = Convert.ToInt16(dtpEdit.Value.[Date].ToString("dd"))
'MessageBox.Show(a.ToString() + b.ToString());
'yyyyF<S
'MMF<S
'ddF<S
If yyyy < Convert.ToInt16(DateTime.Now.ToString("yyyy")) Then
MessageBox.Show("กรุณาตรวจสอบปี")
ElseIf yyyy = Convert.ToInt16(DateTime.Now.ToString("yyyy")) AndAlso MM <
Convert.ToInt16(DateTime.Now.ToString("MM")) Then
MessageBox.Show("กรุณาตรวจสอบเดือน")
ElseIf yyyy = Convert.ToInt16(DateTime.Now.ToString("yyyy")) AndAlso MM =
Convert.ToInt16(DateTime.Now.ToString("MM")) AndAlso dd <
Convert.ToInt16(DateTime.Now.ToString("dd")) Then
MessageBox.Show("กรุณาตรวจสอบวัน")
Else
'2. Sql statement //ลงตาราง tb_PricePerson (DateStart,Child,Adult,Datefinish)
Dim strSql As [String] = (Convert.ToString("Insert into tb_PricePerson
(DateEdit,Adult,Child)values(" + " '") & dateEdit) + "'" + ",'" + txtChild.Text + "'" + ",'" +
txtAdult.Text + "'" + ")"
'3. สั่ง Sql statement ทางาน
Dim cmd As New SqlCommand(strSql, connectDB)
cmd.ExecuteNonQuery()
'3.1
MessageBox.Show("บันทึกหน้าจอเรียบร้อยแล้ว")
End If
'4.close DB
connectDB.Close()
loadDataToPricePeople()
End If
28
End Sub
'MsgBox(txtAdult.Text & " " & txtChild.Text & " " & dtpFinish.Text)
'If True Then
' '1.ติดต่อฐานข้อมูล
' 'string conStr = "server=ISIN;initial catalog=DBBarBQ;integrated security=true";
' Dim conStr As String = "server=Localhost;initial catalog=DBBarBQ;integrated
security=true"
' Dim connectDB As New SqlConnection(conStr)
' If connectDB.State = ConnectionState.Open Then
' connectDB.Close()
' End If
' Try
' 'MessageBox.Show("โอเคผ่าน");
' connectDB.Open()
' Catch ex As Exception
' MessageBox.Show("can't Database open." + ex.Message)
' Return
' End Try
' 'string dateS = dtpFinish.Value.Date.ToShortDateString();
' Dim dateS As String = DateTime.Now.ToString("yyyy-MM-dd " + "hh:mm:ss.fff")
' Dim YYYYF As String = (Convert.ToInt16(dtpFinish.Value.[Date].ToString("yyyy")) -
543).ToString("0000")
' Dim dateF As String = dtpFinish.Value.[Date].ToString((YYYYF & Convert.ToString("-MM-dd
")) + "hh:mm:ss.fff")
' Dim yyyy As Integer = Convert.ToInt16(dtpFinish.Value.[Date].ToString("yyyy"))
' Dim MM As Integer = Convert.ToInt16(dtpFinish.Value.[Date].ToString("MM"))
' Dim dd As Integer = Convert.ToInt16(dtpFinish.Value.[Date].ToString("dd"))
' 'MessageBox.Show(a.ToString() + b.ToString());
' 'yyyyF<S
' 'MMF<S
' 'ddF<S
' If yyyy < Convert.ToInt16(DateTime.Now.ToString("yyyy")) Then
' MessageBox.Show("กรุณาตรวจสอบปี")
' ElseIf yyyy = Convert.ToInt16(DateTime.Now.ToString("yyyy")) AndAlso MM <
Convert.ToInt16(DateTime.Now.ToString("MM")) Then
' MessageBox.Show("กรุณาตรวจสอบเดือน")
' ElseIf yyyy = Convert.ToInt16(DateTime.Now.ToString("yyyy")) AndAlso MM =
Convert.ToInt16(DateTime.Now.ToString("MM")) AndAlso dd <
Convert.ToInt16(DateTime.Now.ToString("dd")) Then
' MessageBox.Show("กรุณาตรวจสอบวัน")
' Else
' '2. Sql statement //ลงตาราง tb_PricePerson (DateStart,Child,Adult,Datefinish)
' '+ ",'" + txtAdult.Text + "'"
' '+ ", 2558-09-04 00:00:00 "
' Dim strSql As [String] = (Convert.ToString((Convert.ToString("Insert into
tb_PricePerson (DateStart,Adult,Child,Datefinish)values(" + " '") & dateS) + "'" + ",'" +
txtAdult.Text + "'" + ",'" + txtChild.Text + "'" + ",'") & dateF) + "'" + ")"
' '3. สั่ง Sql statement ทางาน
' Dim cmd As New SqlCommand(strSql, connectDB)
' cmd.ExecuteNonQuery()
' '3.1
29
' MessageBox.Show("บันทึกหน้าจอเรียบร้อยแล้ว")
' End If
' '4.close DB
' connectDB.Close()
' loadDataToPricePeople()
'End If
Private Sub btnEditAdult_Click(sender As Object, e As EventArgs)
txtAdult.Enabled = True
txtAdult.Focus()
End Sub
Private Sub btnEditChild_Click(sender As Object, e As EventArgs)
txtChild.Enabled = True
txtChild.Focus()
End Sub
Private Sub Label6_Click(sender As Object, e As EventArgs) Handles Label6.Click
End Sub
Private Sub btnEditDateFinish_Click_1(sender As Object, e As EventArgs) Handles
btnEditDateFinish.Click
txtAdult.Enabled = True
txtAdult.Focus()
txtChild.Enabled = True
dtpEdit.Enabled = True
End Sub
Private Sub txtAdult_KeyDown(sender As Object, e As KeyEventArgs) Handles txtAdult.KeyDown
If e.KeyCode = Keys.Enter Then
txtChild.Focus()
End If
End Sub
Private Sub txtChild_KeyDown(sender As Object, e As KeyEventArgs) Handles txtChild.KeyDown
If e.KeyCode = Keys.Enter Then
dtpEdit.Focus()
End If
End Sub
End Class
30
โค๊ด combobox ดึงข้อมูลออกมำ จำก Db
Dim strConnString As String
strConnString = "Server=localhost;User Id=root; Password=root; Database=mydatabase; Pooling=false"
objConn = New MySqlConnection(strConnString)
objConn.Open()
Dim sqlGeo As String = "SELECT geo_name FROM geography"
Dim daGeo As New MySqlDataAdapter(sqlGeo, con)
Dim dtGeo As New DataTable
daGeo.Fill(dtGeo)
With cmbGeo
.DataSource = dtGeo
.DisplayMember = dtGeo.Columns.Item("geo_name").ColumnName
End With
ต้องกำร ให้ลบแถวที่เรำเลือกไว้ ลบ โดย ใช้ปุ่ม del ปกติ ให้มีข้อควำมเตือนและสำมำรถลบได้ปกตำมที่ defalut
niras srihemthong:
Private Sub DataGridView1_KeyDown(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) _
Handles DataGridView1.KeyDown
Dim CurRow As Integer
CurRow = Me.DataGridView1.CurrentRow.Index
If e.KeyCode = Keys.Delete Then
If Me.DataGridView1.Rows.Count <> 1 Then
Dim Result As MsgBoxResult
Result = MessageBox.Show("ต้องกำรลบข้อมูลแถวนี้หรือไม่", "ยืนยัน", MessageBoxButtons.YesNo, _
MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
31
If Result = MsgBoxResult.Yes Then
Me.DataGridView1.Rows.RemoveAt(CurRow)
End If
End If
End If
End Sub
ผมว่ำผูกข้อมูลโดยกำรเขียนโค้ดจะดีกว่ำในกรณีต้องกำร refresh ข้อมูลใหม่บ่อยหรือมีกำรใช้งำนร่วมกันหลำย ๆ ฟอร์ม ถ้ำจะอธิบำยก็คงต้องเริ่มตั้งแต่กำร เขียนโค้ดในกำรผูก
ข้อมูลตั้งแต่เริ่มแรกเลยไม่ยำกครับลองแกะดูครับ ผมก็อำศัยวิธีเดียวกับคุณนั้นแหละ เพรำะว่ำหนังสือไทยไม่มีเลย ก็ต้องไปหำอ่ำนตำมเว็บเมืองนอก
ผมจะเขียนแบบนี้ครับ
Imports System.Data.OleDb 'เรียกใช้เฟรมเวิร์ก
Public Class form1
Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
Windows.Forms.Application.StartupPath & "databaseMyDataBase.mdb;Jet OLEDB:Database Password=1234;"
'กำหนด พำร์ทของฐำนข้อมูลครับ ในที่นี้เป็นฐำนข้อมูล Access ชื่อว่ำ MyDataBase.mdb password 1234 ถ้ำมีกำรตั้ง password ใน access คำสั่ง StartupPath เป็น
คำสั่งระบุว่ำ ฐำนข้อมูลนี้อยู่ภำยในโฟลเดอร์เดียวกันกับโปรแกรม และอยู่ภำยใน ซับโฟล์เดอร์ ที่ชื่อว่ำ database
Dim Conn As New OleDbConnection(strConn) ' เรียกใช้คำสั่ง ติดต่อฐำนข้อมูล
Dim ds As New DataSet 'กำหนดตัวแปรเป็นแบบดำต้ำเซ็ท ตัวแปรนี้แหละครับจะเป็นตัว refresh ข้อมูล
Private Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim StrSql As String
StrSql = "SELECT * FROM MyTable " 'คำสั่ง SQL
Dim da As OleDbDataAdapter 'ตัวแปรนี้ก็คือ DataAdapter ที่คุณใช้ใน Tool ครับ
da = New OleDbDataAdapter(StrSql, Conn) 'เก็บข้อมูลจำกกำรเรียกใช้คำสั่ง SQL เข้ำมำใน DataAdapter
da.Fill(ds, "MyData") 'นำเข้ำมูล จำก DataAdapter มำเก็บไว้ ในดำต้ำเซ็ทที่ชื่อ ds ครับ ds เป็นดำต้ำเซ็ทที่ใช้ในกำรพักข้อมูลก่อนส่งเข้ำไปแสดงที่ดำต้ำกริด
Mydata เป็นชื่อที่ตั้งเพื่อสื่อควำมหมำยแทนข้อมูลในดำต้ำเซ็ทครับ
Me.DataGridView1.DataSource = ds.Tables("MyData") 'นำข้อมูลที่ได้มำแสดงที่ดำต้ำกริดครับ
End Sub
32
End Class
ต่อไปก็จะเป็นกำร รีเฟรชข้อมูลครับ
ใช้คำสั่งนี้
If ds.Tables.Contains("MyData") Then 'ก็จะตรวจสอบ ข้อมูลค้ำงอยู่ใน ดำต้ำเซ็ทไหม ถ้ำมีค้ำงอยู่ใน รีมูฟ ออกก่อน
ds.Tables.Remove("MyData")
End If
ก็เป็นกำรตัดกำรผูกข้อมูลกับฐำนข้อมูล ถ้ำจะมีกำรดึงข้อมูลขึ้นมำอีกก็ทำตำมโค้ดข้ำงบนเหมือนเดิม คุณต้องทำควำมเข้ำใจกับ ตัวแปร ds หรือ ดำต้ำเซ็ทก่อนนะครับ ดำต้ำเซ็ท
เป็นตำรำงข้อมูลในรูปแบบ temporary ดูง่ำย ๆ เหมือนไฟล์เอ็กเซลที่เก็บไว้ในหน่วยควำมจำ ดำต้ำเซ็ทสำมำรถมีได้หลำยตำรำงเหมือนกับเอ็กเซลก็สำมำรถมีได้หลำย sheet คุณ
สำมำรถ fill เข้ำดำต้ำเซ็ทได้หลำยตำรำงก็ได้ เช่น da.Fill(ds, "MyData") หรือ da.Fill(ds, "MyData1 ") , da.Fill(ds, "MyDataN") จำก da หรือ DataAdapter ตัว
เดียวกันได้
Public Class frmMain
'By http://www.thaicreate.com (mr.win)'
Private Sub btnHome_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHome.Click
Me.Hide()
Dim f As New frmHome
f.Show()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
If MessageBox.Show("Are you sure to exit?", "Confirm.", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1) = DialogResult.Yes Then
Application.Exit()
End If
End Sub
End Class
Imports System.Data
Imports System.Data.SqlServerCe
Imports System.Data.SqlTypes
33
Imports System.Drawing
Imports System.ComponentModel
Imports System.Windows.Forms
Public Class frmHome
'By http://www.thaicreate.com (mr.win)'
Private Sub frmHome_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
BindDataGrid()
End Sub
Private Sub BindDataGrid()
Dim myConnection As SqlCeConnection
Dim dt As New DataTable
Dim Adapter As SqlCeDataAdapter
'myConnection = New SqlCeConnection("Data Source =" + (System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase ) + "Database1.sdf;"))
myConnection = New SqlCeConnection("Data Source=C:WindowsFormsApplicationWindowsFormsApplicationDatabase1.sdf;")
myConnection.Open()
Dim myCommand As SqlCeCommand = myConnection.CreateCommand()
myCommand.CommandText = "SELECT [id], [name], [email] FROM [mytable]"
myCommand.CommandType = CommandType.Text
Adapter = New SqlCeDataAdapter(myCommand)
Adapter.Fill(dt)
myConnection.Close()
Me.dgName.DataSource = dt
Me.dgName.Columns.Clear()
34
Dim column As DataGridViewTextBoxColumn
column = New DataGridViewTextBoxColumn()
column.DataPropertyName = "id"
column.HeaderText = "ID"
column.Width = 50
Me.dgName.Columns.Add(column)
column = New DataGridViewTextBoxColumn()
column.DataPropertyName = "name"
column.HeaderText = "Name"
column.Width = 100
Me.dgName.Columns.Add(column)
column = New DataGridViewTextBoxColumn()
column.DataPropertyName = "email"
column.HeaderText = "Email"
column.Width = 150
Me.dgName.Columns.Add(column)
dt = Nothing
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Me.Hide()
Dim f As New frmAdd
f.Show()
End Sub
35
Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
Me.Hide()
Dim f As New frmEdit()
f._strID = Me.dgName(0, Me.dgName.CurrentCell.RowIndex).Value.ToString()
f.Show()
End Sub
Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDel.Click
If MessageBox.Show("Are you sure to delete?", "Confirm.", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1) = DialogResult.Yes Then
Dim strID As String = Me.dgName(0, Me.dgName.CurrentCell.RowIndex).Value.ToString()
Dim myConnection As SqlCeConnection
'myConnection = New SqlCeConnection("Data Source =" + (System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase ) + "Database1.sdf;"))
myConnection = New SqlCeConnection("Data Source=C:WindowsFormsApplicationWindowsFormsApplicationDatabase1.sdf;")
myConnection.Open()
Dim myCommand As SqlCeCommand = myConnection.CreateCommand()
myCommand.CommandText = "DELETE FROM [mytable] WHERE id = '" & strID & "'"
myCommand.CommandType = CommandType.Text
myCommand.ExecuteNonQuery()
myConnection.Close()
MessageBox.Show("Delete Successfully")
BindDataGrid()
End If
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Hide()
Dim f As New frmMain
36
f.Show()
End Sub
End Class
Imports System.Data
Imports System.Data.SqlServerCe
Imports System.Data.SqlTypes
Imports System.Drawing
Imports System.ComponentModel
Imports System.Windows.Forms
Public Class frmAdd
'By http://www.thaicreate.com (mr.win)'
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
If Me.txtName.Text = "" Then
MessageBox.Show("Please input (Name)")
Me.txtName.Focus()
Exit Sub
End If
If Me.txtEmail.Text = "" Then
MessageBox.Show("Please input (Email)")
Me.txtEmail.Focus()
Exit Sub
End If
Dim myConnection As SqlCeConnection
'myConnection = New SqlCeConnection("Data Source =" + (System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase ) + "Database1.sdf;"))
37
myConnection = New SqlCeConnection("Data Source=C:WindowsFormsApplicationWindowsFormsApplicationDatabase1.sdf;")
myConnection.Open()
Dim myCommand As SqlCeCommand = myConnection.CreateCommand()
myCommand.CommandText = "INSERT INTO [mytable] ([name], [email]) VALUES " & _
" ('" & Me.txtName.Text & "','" & Me.txtEmail.Text & "' ) "
myCommand.CommandType = CommandType.Text
myCommand.ExecuteNonQuery()
myConnection.Close()
MessageBox.Show("Save Successfully.")
Me.Hide()
Dim f As New frmHome
f.Show()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Hide()
Dim f As New frmHome
f.Show()
End Sub
End Class
Imports System.Data
Imports System.Data.SqlServerCe
Imports System.Data.SqlTypes
Imports System.Drawing
Imports System.ComponentModel
Imports System.Windows.Forms
Public Class frmEdit
38
'By http://www.thaicreate.com (mr.win)'
Dim strID As String = ""
Public Property _strID() As String
Get
Return strID
End Get
Set(ByVal value As String)
strID = value
End Set
End Property
Private Sub frmEdit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim myConnection As SqlCeConnection
Dim dt As New DataTable
Dim Adapter As SqlCeDataAdapter
'myConnection = New SqlCeConnection("Data Source =" + (System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase ) + "Database1.sdf;"))
myConnection = New SqlCeConnection("Data Source=C:WindowsFormsApplicationWindowsFormsApplicationDatabase1.sdf;")
myConnection.Open()
Dim myCommand As SqlCeCommand = myConnection.CreateCommand()
myCommand.CommandText = "SELECT [id], [name], [email] FROM [mytable] WHERE id = '" & strID & "' "
myCommand.CommandType = CommandType.Text
Adapter = New SqlCeDataAdapter(myCommand)
Adapter.Fill(dt)
myConnection.Close()
If dt.Rows.Count > 0 Then
Me.txtName.Text = dt.Rows(0)("name")
39
Me.txtEmail.Text = dt.Rows(0)("email")
End If
dt = Nothing
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
If Me.txtName.Text = "" Then
MessageBox.Show("Please input (Name)")
Me.txtName.Focus()
Exit Sub
End If
If Me.txtEmail.Text = "" Then
MessageBox.Show("Please input (Email)")
Me.txtEmail.Focus()
Exit Sub
End If
Dim myConnection As SqlCeConnection
'myConnection = New SqlCeConnection("Data Source =" + (System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase ) + "Database1.sdf;"))
myConnection = New SqlCeConnection("Data Source=C:WindowsFormsApplicationWindowsFormsApplicationDatabase1.sdf;")
myConnection.Open()
Dim myCommand As SqlCeCommand = myConnection.CreateCommand()
myCommand.CommandText = "UPDATE [mytable] SET " & _
" [name] = '" & Me.txtName.Text & "', [email] = '" & Me.txtEmail.Text & "' " & _
" WHERE id = '" & strID & "' "
myCommand.CommandType = CommandType.Text
myCommand.ExecuteNonQuery()
40
myConnection.Close()
MessageBox.Show("Update Successfully")
Me.Hide()
Dim f As New frmHome
f.Show()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Hide()
Dim f As New frmHome
f.Show()
End Sub
End Class

More Related Content

What's hot

Functions
FunctionsFunctions
Functions
G.C Reddy
 
โค้ด
โค้ดโค้ด
โค้ด
MareenaHahngeh
 
Is2215 lecture8 relational_databases
Is2215 lecture8 relational_databasesIs2215 lecture8 relational_databases
Is2215 lecture8 relational_databases
dannygriff1
 
The Ring programming language version 1.3 book - Part 7 of 88
The Ring programming language version 1.3 book - Part 7 of 88The Ring programming language version 1.3 book - Part 7 of 88
The Ring programming language version 1.3 book - Part 7 of 88
Mahmoud Samir Fayed
 
Android
AndroidAndroid
Android
ZÅhid IslÅm
 
Qtp best tutorial
Qtp best tutorialQtp best tutorial
Qtp best tutorial
Ramu Palanki
 
syed
syedsyed
Rental
RentalRental
Rental
Ahmad M
 
The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196
Mahmoud Samir Fayed
 
Mobile Web 5.0
Mobile Web 5.0Mobile Web 5.0
Mobile Web 5.0
Michael Galpin
 
Id32
Id32Id32
Id32
sandhish
 
Pymongo for the Clueless
Pymongo for the CluelessPymongo for the Clueless
Pymongo for the Clueless
Chee Leong Chow
 
Qtp realtime scripts
Qtp realtime scriptsQtp realtime scripts
Qtp realtime scripts
Ramu Palanki
 
java experiments and programs
java experiments and programsjava experiments and programs
java experiments and programs
Karuppaiyaa123
 
The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202
Mahmoud Samir Fayed
 
Assist9 bmis
Assist9 bmisAssist9 bmis
Assist9 bmis
vbahelper94
 
OOP - PREFINAL ACTIVITY - ACLC
OOP - PREFINAL ACTIVITY - ACLCOOP - PREFINAL ACTIVITY - ACLC
OOP - PREFINAL ACTIVITY - ACLC
Marlo Tinio
 
The Ring programming language version 1.9 book - Part 78 of 210
The Ring programming language version 1.9 book - Part 78 of 210The Ring programming language version 1.9 book - Part 78 of 210
The Ring programming language version 1.9 book - Part 78 of 210
Mahmoud Samir Fayed
 

What's hot (18)

Functions
FunctionsFunctions
Functions
 
โค้ด
โค้ดโค้ด
โค้ด
 
Is2215 lecture8 relational_databases
Is2215 lecture8 relational_databasesIs2215 lecture8 relational_databases
Is2215 lecture8 relational_databases
 
The Ring programming language version 1.3 book - Part 7 of 88
The Ring programming language version 1.3 book - Part 7 of 88The Ring programming language version 1.3 book - Part 7 of 88
The Ring programming language version 1.3 book - Part 7 of 88
 
Android
AndroidAndroid
Android
 
Qtp best tutorial
Qtp best tutorialQtp best tutorial
Qtp best tutorial
 
syed
syedsyed
syed
 
Rental
RentalRental
Rental
 
The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196
 
Mobile Web 5.0
Mobile Web 5.0Mobile Web 5.0
Mobile Web 5.0
 
Id32
Id32Id32
Id32
 
Pymongo for the Clueless
Pymongo for the CluelessPymongo for the Clueless
Pymongo for the Clueless
 
Qtp realtime scripts
Qtp realtime scriptsQtp realtime scripts
Qtp realtime scripts
 
java experiments and programs
java experiments and programsjava experiments and programs
java experiments and programs
 
The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202
 
Assist9 bmis
Assist9 bmisAssist9 bmis
Assist9 bmis
 
OOP - PREFINAL ACTIVITY - ACLC
OOP - PREFINAL ACTIVITY - ACLCOOP - PREFINAL ACTIVITY - ACLC
OOP - PREFINAL ACTIVITY - ACLC
 
The Ring programming language version 1.9 book - Part 78 of 210
The Ring programming language version 1.9 book - Part 78 of 210The Ring programming language version 1.9 book - Part 78 of 210
The Ring programming language version 1.9 book - Part 78 of 210
 

Similar to Vb Project ขั้นเทพ

SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)
Darwin Durand
 
Kode vb.net
Kode vb.netKode vb.net
Kode vb.net
Azki Nabidin
 
Sistemadeventas 100707084319-phpapp01
Sistemadeventas 100707084319-phpapp01Sistemadeventas 100707084319-phpapp01
Sistemadeventas 100707084319-phpapp01
mafv1976
 
Inventory management
Inventory managementInventory management
Inventory management
Rajeev Sharan
 
Codes
CodesCodes
Codes
OSit3
 
Reservasi hotel
Reservasi hotelReservasi hotel
Reservasi hotel
dian pw
 
Membuat aplikasi penjualan buku sederhana
Membuat aplikasi penjualan buku sederhanaMembuat aplikasi penjualan buku sederhana
Membuat aplikasi penjualan buku sederhana
Yusman Kurniadi
 
Vb.net programs
Vb.net programsVb.net programs
The Ring programming language version 1.7 book - Part 41 of 196
The Ring programming language version 1.7 book - Part 41 of 196The Ring programming language version 1.7 book - Part 41 of 196
The Ring programming language version 1.7 book - Part 41 of 196
Mahmoud Samir Fayed
 
Vb file
Vb fileVb file
.Net Enterprise Services and their Implementations
.Net Enterprise Services and their Implementations.Net Enterprise Services and their Implementations
.Net Enterprise Services and their Implementations
Kashif Aleem
 
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31
Mahmoud Samir Fayed
 
Inventory program in mca p1
Inventory program in mca p1Inventory program in mca p1
Inventory program in mca p1
rameshvvv
 
Form1.vb
Form1.vbForm1.vb
Form1.vb
Like Music
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210
Mahmoud Samir Fayed
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010
RonnBlack
 
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVERINSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
Darwin Durand
 
VB net lab.pdf
VB net lab.pdfVB net lab.pdf
VB net lab.pdf
Prof. Dr. K. Adisesha
 
please code in c#- please note that im a complete beginner- northwind.docx
please code in c#- please note that im a complete beginner-  northwind.docxplease code in c#- please note that im a complete beginner-  northwind.docx
please code in c#- please note that im a complete beginner- northwind.docx
AustinaGRPaigey
 

Similar to Vb Project ขั้นเทพ (20)

SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)
 
Kode vb.net
Kode vb.netKode vb.net
Kode vb.net
 
Sistemadeventas 100707084319-phpapp01
Sistemadeventas 100707084319-phpapp01Sistemadeventas 100707084319-phpapp01
Sistemadeventas 100707084319-phpapp01
 
Inventory management
Inventory managementInventory management
Inventory management
 
Codes
CodesCodes
Codes
 
Reservasi hotel
Reservasi hotelReservasi hotel
Reservasi hotel
 
Membuat aplikasi penjualan buku sederhana
Membuat aplikasi penjualan buku sederhanaMembuat aplikasi penjualan buku sederhana
Membuat aplikasi penjualan buku sederhana
 
Vb.net programs
Vb.net programsVb.net programs
Vb.net programs
 
The Ring programming language version 1.7 book - Part 41 of 196
The Ring programming language version 1.7 book - Part 41 of 196The Ring programming language version 1.7 book - Part 41 of 196
The Ring programming language version 1.7 book - Part 41 of 196
 
Vb file
Vb fileVb file
Vb file
 
.Net Enterprise Services and their Implementations
.Net Enterprise Services and their Implementations.Net Enterprise Services and their Implementations
.Net Enterprise Services and their Implementations
 
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31
 
Inventory program in mca p1
Inventory program in mca p1Inventory program in mca p1
Inventory program in mca p1
 
Form1.vb
Form1.vbForm1.vb
Form1.vb
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010
 
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVERINSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
 
VB net lab.pdf
VB net lab.pdfVB net lab.pdf
VB net lab.pdf
 
please code in c#- please note that im a complete beginner- northwind.docx
please code in c#- please note that im a complete beginner-  northwind.docxplease code in c#- please note that im a complete beginner-  northwind.docx
please code in c#- please note that im a complete beginner- northwind.docx
 

Recently uploaded

How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Undress Baby
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
aymanquadri279
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 

Recently uploaded (20)

How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 

Vb Project ขั้นเทพ

  • 1. 1 Imports System.Data.SqlClient Public Class FrmSaleProduct Private Sub tsbtnAdd_Click(sender As Object, e As EventArgs) Handles tsbtnAdd.Click Dim conn As SqlConnection conn = New SqlConnection("Data Source = ISIN; Database=DBSale; integrated security=true") If conn.State = ConnectionState.Open Then conn.Close() conn.Open() Dim strSql As String strSql = "SELECT TOP 1 BillID FROM tb_Sale ORDER BY BillID DESC" Dim da As New SqlDataAdapter(strSql, conn) Dim ds As New DataSet da.Fill(ds, "Sale") 'นำค่ำ da ใส่ใน ds ชื่อ product555 If ds.Tables("Sale").Rows.Count = 0 Then txtBillid.Text = DateTime.Now.ToString("yy-MM") + "-" + "0001" Else Dim oldBillID As String = ds.Tables("Sale").Rows(0).Item("BillID").ToString().Substring(6) Dim newBillID As String = (Convert.ToInt32(oldBillID) + 1).ToString("0000") txtBillid.Text = DateTime.Now.ToString("yy-MM") + "-" + newBillID End If
  • 2. 2 conn.Close() dtpSaleDate.Enabled = True txtCustomerId.Enabled = True btnSelectCustomer.Enabled = True txtProductId.Enabled = True btnSelectProduct.Enabled = True txtAmount.Enabled = True btnAddProductSale.Enabled = True tsbtnSave.Enabled = True tsbtnAdd.Enabled = False End Sub Private Sub btnSelectCustomer_Click(sender As Object, e As EventArgs) Handles btnSelectCustomer.Click dgvSelectCustomer.Visible = True Dim conn As SqlConnection conn = New SqlConnection("Data Source = ISIN; Database=DBSale; integrated security=true") If conn.State = ConnectionState.Open Then conn.Close() conn.Open() 'If conn.State = ConnectionState.Open Then MessageBox.Show("Connection OK") Dim strSql As String strSql = "SELECT CustomerId, Name FROM tb_Customers" Dim da As New SqlDataAdapter(strSql, conn) Dim ds As New DataSet da.Fill(ds, "Customers") dgvSelectCustomer.DataSource = ds.Tables("Customers") conn.Close() dgvSelectCustomer.Columns(0).HeaderText = "รหัสลูกค้ำ" dgvSelectCustomer.Columns(1).HeaderText = "ชื่อลูกค้ำ" dgvSelectCustomer.Columns(0).Width = 100 dgvSelectCustomer.Columns(1).Width = 150 End Sub Private Sub txtCustomerId_KeyUp(sender As Object, e As KeyEventArgs) Handles txtCustomerId.KeyUp Dim conn As SqlConnection conn = New SqlConnection("Data Source = ISIN; Database=DBSale; integrated security=true") If conn.State = ConnectionState.Open Then conn.Close() conn.Open()
  • 3. 3 Dim strSql As String = "SELECT CustomerId, Name FROM tb_Customers Where CustomerID = '" + txtCustomerId.Text + "'" Dim da As New SqlDataAdapter(strSql, conn) Dim ds As New DataSet da.Fill(ds, "Customers") 'นำค่ำ da ใส่ใน ds ชื่อ product555 If ds.Tables("Customers").Rows.Count = 0 Then txtName.Text = "" Else txtName.Text = ds.Tables("Customers").Rows(0).Item("Name").ToString() End If conn.Close() End Sub Private Sub dgvSelectCustomer_CellMouseUp(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvSelectCustomer.CellMouseUp If e.RowIndex < 0 Then Exit Sub End If txtCustomerId.Text = dgvSelectCustomer.Rows(e.RowIndex).Cells(0).Value.ToString() txtName.Text = dgvSelectCustomer.Rows(e.RowIndex).Cells(1).Value.ToString() dgvSelectCustomer.Visible = False End Sub Private Sub txtProductId_KeyUp(sender As Object, e As KeyEventArgs) Handles txtProductId.KeyUp Dim conn As SqlConnection conn = New SqlConnection("Data Source = ISIN; Database=DBSale; integrated security=true") If conn.State = ConnectionState.Open Then conn.Close() conn.Open() Dim strSql As String = "SELECT * FROM tb_Products Where ProductID = '" + txtProductId.Text + "'" Dim da As New SqlDataAdapter(strSql, conn) Dim ds As New DataSet da.Fill(ds, "Products") 'นำค่ำ da ใส่ใน ds ชื่อ product555 If ds.Tables("Products").Rows.Count = 0 Then txtProductName.Text = "" txtUnitsInstock.Text = "" txtSalePrice.Text = "" Else txtProductName.Text = ds.Tables("Products").Rows(0).Item("ProductName").ToString() txtUnitsInstock.Text = ds.Tables("Products").Rows(0).Item("UnitsInstock").ToString() txtSalePrice.Text = ds.Tables("Products").Rows(0).Item("SalePrice").ToString() End If conn.Close() End Sub Private Sub btnSelectProduct_Click(sender As Object, e As EventArgs) Handles btnSelectProduct.Click
  • 4. 4 dgvSelectProduct.Visible = True Dim conn As SqlConnection conn = New SqlConnection("Data Source = ISIN; Database=DBSale; integrated security=true") If conn.State = ConnectionState.Open Then conn.Close() conn.Open() 'If conn.State = ConnectionState.Open Then MessageBox.Show("Connection OK") Dim strSql As String = "SELECT ProductID, ProductName, UnitsInstock, SalePrice FROM tb_Products" Dim da As New SqlDataAdapter(strSql, conn) Dim ds As New DataSet da.Fill(ds, "Products") dgvSelectProduct.DataSource = ds.Tables("Products") conn.Close() dgvSelectProduct.Columns(0).HeaderText = "รหัสสินค้ำ" dgvSelectProduct.Columns(1).HeaderText = "ชื่อสินค้ำ" dgvSelectProduct.Columns(2).HeaderText = "จำนวนในสต็อก" dgvSelectProduct.Columns(3).HeaderText = "รำคำขำย" dgvSelectProduct.Columns(0).Width = 100 dgvSelectProduct.Columns(1).Width = 150 dgvSelectProduct.Columns(2).Width = 120 dgvSelectProduct.Columns(3).Width = 100 End Sub Private Sub dgvSelectProduct_CellMouseUp(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvSelectProduct.CellMouseUp If e.RowIndex < 0 Then Exit Sub End If txtProductId.Text = dgvSelectProduct.Rows(e.RowIndex).Cells(0).Value.ToString() txtProductName.Text = dgvSelectProduct.Rows(e.RowIndex).Cells(1).Value.ToString() txtUnitsInstock.Text = dgvSelectProduct.Rows(e.RowIndex).Cells(2).Value.ToString() txtSalePrice.Text = dgvSelectProduct.Rows(e.RowIndex).Cells(3).Value.ToString() dgvSelectProduct.Visible = False End Sub Private Sub btnAddProductSale_Click(sender As Object, e As EventArgs) Handles btnAddProductSale.Click If txtProductName.Text = "" Then MessageBox.Show("เลือกสินค้ำ") ElseIf txtAmount.Text = "" Then MessageBox.Show("กรุณำกรอกจำนวนที่ซื้อ") ElseIf Convert.ToInt32(txtAmount.Text) > Convert.ToInt32(txtUnitsInstock.Text) Then MessageBox.Show("จำนวนที่ซื้อมำกกว่ำ สินค้ำในสต็อก") Else Dim dgvRow As Integer = dgvSaleDetail.Rows.Count
  • 5. 5 If dgvRow <> 0 Then For i As Integer = 0 To dgvRow - 1 If dgvSaleDetail.Rows(i).Cells(0).Value.ToString() = txtProductId.Text Then Dim quantity As Integer = Convert.ToInt32(txtAmount.Text) + Convert.ToInt32(dgvSaleDetail.Rows(i).Cells(3).Value) If quantity > Convert.ToInt32(txtUnitsInstock.Text) Then MessageBox.Show("จำนวนที่ซื้อมำกกว่ำ สินค้ำในสต็อก") Else dgvSaleDetail.Rows(i).Cells(3).Value = quantity Dim saleUpdate As Double = quantity * Convert.ToDouble(txtSalePrice.Text) dgvSaleDetail.Rows(i).Cells(4).Value = saleUpdate Dim saleTotalUpdate = Convert.ToDouble(lblTotal.Text) + (Convert.ToInt32(txtAmount.Text) * Convert.ToDouble(txtSalePrice.Text)) lblTotal.Text = saleTotalUpdate.ToString("#,##0.00") End If txtProductId.Clear() txtUnitsInstock.Clear() txtProductName.Clear() txtSalePrice.Clear() txtAmount.Clear() Exit Sub End If Next End If Dim numRow = dgvSaleDetail.Rows.Add() dgvSaleDetail.Rows(numRow).Cells(0).Value = txtProductId.Text dgvSaleDetail.Rows(numRow).Cells(1).Value = txtProductName.Text dgvSaleDetail.Rows(numRow).Cells(2).Value = txtSalePrice.Text dgvSaleDetail.Rows(numRow).Cells(3).Value = txtAmount.Text Dim salePrice As Double = Convert.ToInt32(txtAmount.Text) * Convert.ToDouble(txtSalePrice.Text) dgvSaleDetail.Rows(numRow).Cells(4).Value = salePrice Dim saleTotal As Double = Convert.ToDouble(lblTotal.Text) + salePrice lblTotal.Text = saleTotal.ToString("#,##0.00") txtProductId.Clear() txtUnitsInstock.Clear() txtProductName.Clear() txtSalePrice.Clear() txtAmount.Clear() End If End Sub Private Sub dgvSaleDetail_CellMouseDoubleClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvSaleDetail.CellMouseDoubleClick Dim rowSelect As Integer = e.RowIndex
  • 6. 6 Dim total As Double = Convert.ToDouble(lblTotal.Text) - Convert.ToDouble(dgvSaleDetail.Rows(rowSelect).Cells(4).Value.ToString()) lblTotal.Text = total.ToString("#,##0.00") dgvSaleDetail.Rows.RemoveAt(rowSelect) End Sub Private Sub tsbtnSave_Click(sender As Object, e As EventArgs) Handles tsbtnSave.Click If txtName.Text = "" Then MessageBox.Show("เลือกชื่อลูกค้ำด้วย") ElseIf dgvSaleDetail.Rows.Count = 0 Then MessageBox.Show("เลือกสินค้ำที่จะซื้อด้วย") Else Dim conn As SqlConnection conn = New SqlConnection("Data Source = ISIN; Database=DBSale; integrated security=true") If conn.State = ConnectionState.Open Then conn.Close() conn.Open() 'If conn.State = ConnectionState.Open Then MessageBox.Show("Connection OK") Dim cm As New SqlCommand cm.Connection = conn cm.CommandType = CommandType.Text Dim strSql As String strSql = "insert into tb_sale (billId, saleDate, customerId, total) values ('" + txtBillid.Text + "', '" + dtpSaleDate.Value.Date.ToString("yyyy-MM-dd", New System.Globalization.CultureInfo("en-US")) + "', '" + txtCustomerId.Text + "', " + lblTotal.Text + ")" cm.CommandText = strSql cm.ExecuteNonQuery() MessageBox.Show("บันทึกเรียบร้อยแล้ว") conn.Close() End If End Sub End Class Save File Dialog Confirm Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click SaveFileDialog1.DefaultExt = "*.rtf" SaveFileDialog1.Filter = "RTF Files|*.rtf"
  • 7. 7 SaveFileDialog1.CreatePrompt = True If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then RichTextBox1.SaveFile(SaveFileDialog1.FileName, RichTextBoxStreamType.RichText) End If End Sub มินิโปรเจค Imports System.Collections.Generic Imports System.ComponentModel Imports System.Data Imports System.Data.SqlClient Imports System.Drawing Imports System.Linq Imports System.Text Imports System.Windows.Forms
  • 8. 8 Namespace WindowsFormsApplication1 Public Partial Class AddOrder Inherits Form Private btnText As String Public Sub New(btnText As String) InitializeComponent() Me.btnText = btnText End Sub Private Sub loadDataToAdd() Dim nt As Integer = Convert.ToInt16(btnText.Substring(7)) 'sub x Dim T00 As String = "T" + nt.ToString("00") '1.ติดต่อฐำนข้อมูล 'string conStr = "server=Localhost;initial catalog=DBBarBQ;integrated security=true"; Dim conStr As String = "server=Localhost ;initial catalog=DBBarBQ;integrated security=true" Dim connectDB As New SqlConnection(conStr) If connectDB.State = ConnectionState.Open Then connectDB.Close() End If Try 'MessageBox.Show("โอเคผ่ำน"); connectDB.Open() Catch ex As Exception MessageBox.Show("can't Database open." + ex.Message) Return End Try '2.คำสั่ง SQL BillID,TableID,SaleDate,AmountChild,AmountAdult,Total,Fined,AmountFined,Status 'tb_xxxx1 a left join tb_xxxx2 b on a.BillID=b.BillID
  • 9. 9 Dim strSql As String = (Convert.ToString("select * " + " from tb_Sale S left join tb_saledetail SD on S.BillID=SD.BillID" + " where S.status = 'Yes' and S.TableID = '") & T00) + "'" 'สมมติ T01 มี ทำ ถ้ำไม่มี ไม่ทำ '3.สั่งให้ SQl ทำงำน Dim cmd As New SqlCommand(strSql, connectDB) 'ทำงำน Dim dr As SqlDataReader = cmd.ExecuteReader() 'สั่งให้ทำงำน + ดึงค่ำที่ได้มำ '3.1 ทำอะไรก็แล้วแต่ If dr.Read() Then txtBill.Text = dr("BillID").ToString() txtChild.Text = dr("AmountChild").ToString() txtAdult.Text = dr("AmountAdult").ToString() txtAmount.Text = dr("AmountFined").ToString() End If '4. connectDB.Close() '###################################### dgvBev #######################################// If connectDB.State = ConnectionState.Closed Then connectDB.Open() End If If True Then '1.ติดต่อฐำนข้อมูล 'string conStr = "server=Localhost;initial catalog=DBBarBQ;integrated security=true"; 'string conStr2 = "server=Localhost ;initial catalog=DBBarBQ;integrated security=true"; 'SqlConnection connectDB2 = new SqlConnection(conStr2); If connectDB.State = ConnectionState.Open Then connectDB.Close() End If
  • 10. 10 Try 'MessageBox.Show("โอเคผ่ำน"); connectDB.Open() Catch ex As Exception MessageBox.Show("can't Database open." + ex.Message) Return End Try '2.คำสั่ง SQL BillID,TableID,SaleDate,AmountChild,AmountAdult,Total,Fined,AmountFined,Status '2.คำสั่ง SQL BeveragesID ,BeveragesName ,SalePrice ,Cost ,UnitStock Dim strSqlBev As String = "select BeveragesID, BeveragesName , SalePrice , UnitStock from tb_Beverages" 'คำสั่ง '3.สั่งให้ SQl ทำงำน Dim cmd2 As New SqlCommand(strSqlBev, connectDB) 'ทำงำน Dim dr2 As SqlDataReader = cmd2.ExecuteReader() 'สั่งให้ทำงำน + ดึงค่ำที่ได้มำ '3.1 ทำอะไรก็แล้วแต่ เอำไปใส่ใน DataGridview Bevproduct 'connectDB.Close(); While dr2.Read() 'กรณีมีข้อมูล 'MessageBox.Show(dr2["BeveragesID"].ToString()); 'เพิ่มแถวใน GV พร้อมกับกำหนดตัวแปร เก็บหมำยเลขแถว Dim numRow As Integer = dgvBev.Rows.Add() 'numRow = numRow; '3.1 product dgvBev.Rows(numRow).Cells(0).Value = dr2("BeveragesID").ToString() dgvBev.Rows(numRow).Cells(1).Value = dr2("BeveragesName").ToString() dgvBev.Rows(numRow).Cells(2).Value = dr2("UnitStock").ToString() dgvBev.Rows(numRow).Cells(3).Value = dr2("SalePrice").ToString() 'txtProductId.Text = dr2["BeveragesID"].ToString();
  • 11. 11 numRow = numRow + 1 End While 'DataTable dt2 = new DataTable(); 'dt2.Load(dr2);//เก็บสิ่งที่ได้มำ 'dgvAddBev.DataSource = dt2;//เอำสิ่งที่เก็บใส่ DataGridView connectDB.Close() End If '###################################### dgvAddBev #######################################// If connectDB.State = ConnectionState.Closed Then connectDB.Open() End If If True Then 'MessageBox.Show("Op1"); '1.ติดต่อฐำนข้อมูล 'string conStr = "server=Localhost;initial catalog=DBBarBQ;integrated security=true"; 'string conStr2 = "server=Localhost ;initial catalog=DBBarBQ;integrated security=true"; 'SqlConnection connectDB2 = new SqlConnection(conStr2); 'if (connectDB.State == ConnectionState.Closed) connectDB.Open(); If connectDB.State = ConnectionState.Open Then connectDB.Close() End If Try 'MessageBox.Show("โอเคผ่ำน"); connectDB.Open() Catch ex As Exception MessageBox.Show("can't Database open." + ex.Message)
  • 12. 12 Return End Try '2.คำสั่ง SQL BillID,TableID,SaleDate,AmountChild,AmountAdult,Total,Fined,AmountFined,Status '2.คำสั่ง SQL BeveragesID ,BeveragesName ,SalePrice ,Cost ,UnitStock Dim strSqlAddBev As String = (Convert.ToString("select * " + " from tb_SaleDetail SD left join tb_Beverages Bev on SD.BeveragesID=Bev.BeveragesID " + " left join tb_Sale S on SD.BillID=S.BillID " + " where SD.BeveragesID=Bev.BeveragesID " + " and S.status = 'Yes' and S.TableID = '") & T00) + "'" '3.สั่งให้ SQl ทำงำน Dim cmd3 As New SqlCommand(strSqlAddBev, connectDB) 'ทำงำน Dim dr3 As SqlDataReader = cmd3.ExecuteReader() 'สั่งให้ทำงำน + ดึงค่ำที่ได้มำ '3.1 ทำอะไรก็แล้วแต่ เอำไปใส่ใน DataGridview Bevproduct While dr3.Read() 'กรณีมีข้อมูล 'MessageBox.Show(dr3["BeveragesID"].ToString()+"Before"); 'เพิ่มแถวใน GV พร้อมกับกำหนดตัวแปร เก็บหมำยเลขแถว Dim numRow As Integer = dgvAddBev.Rows.Add() 'numRow = numRow; '3.1 product dgvAddBev.Rows(numRow).Cells(0).Value = dr3("BeveragesID").ToString() dgvAddBev.Rows(numRow).Cells(1).Value = dr3("BeveragesName").ToString() dgvAddBev.Rows(numRow).Cells(2).Value = dr3("UnitStock").ToString() dgvAddBev.Rows(numRow).Cells(3).Value = dr3("SalePrice").ToString() 'txtProductId.Text = dr2["BeveragesID"].ToString(); numRow = numRow + 1 End While '
  • 13. 13 ' DataTable dt = new DataTable(); ' dt.Load(dr3);//เก็บสิ่งที่ได้มำ ' int dtnum = dt.Rows.Count; ' MessageBox.Show(dtnum.ToString()); ' if (dtnum > 0) ' { ' dataGridView1.Enabled = true; ' dataGridView1.Visible = true; ' } ' else ' { ' dataGridView1.Enabled = false; ' dataGridView1.Visible = false; ' } ' dataGridView1.DataSource = dt;//เอำสิ่งที่เก็บใส่ DataGridView ' dataGridView1.Columns[0].Width = 100; ' dataGridView1.Columns[1].Width = 250; ' dataGridView1.Columns[2].Width = 150; ' dataGridView1.Columns[3].Width = 150; ' dataGridView1.Columns[4].Width = 150; ' connectDB.Close() End If End Sub Private Sub AddOrder_Load(sender As Object, e As EventArgs) lblTableX.Text = btnText 'โตะที่ x
  • 14. 14 loadDataToAdd() End Sub Private Sub dgvBev_CellMouseUp(sender As Object, e As DataGridViewCellMouseEventArgs) If e.RowIndex = -1 Then Return End If txtBevID.Text = dgvBev.Rows(e.RowIndex).Cells(0).Value.ToString() txtBevName.Text = dgvBev.Rows(e.RowIndex).Cells(1).Value.ToString() txtAmount.Enabled = True txtAmount.Focus() btnAddProductSale.Enabled = True btnDelete.Enabled = True End Sub Private Sub tsbtnHome_Click(sender As Object, e As EventArgs) AddOrder.ActiveForm.Close() End Sub Private Sub chkChild_CheckedChanged(sender As Object, e As EventArgs)
  • 15. 15 If chkChild.Checked Then txtChild.Enabled = True txtChild.Focus() Else txtChild.Enabled = False txtChild.Focus() End If End Sub Private Sub chkAdult_CheckedChanged(sender As Object, e As EventArgs) If chkAdult.Checked Then txtAdult.Enabled = True txtAdult.Focus() Else txtAdult.Enabled = False txtAdult.Focus() End If End Sub Private Sub txtChild_KeyPress(sender As Object, e As KeyPressEventArgs) End Sub Private Sub txtAdult_KeyPress(sender As Object, e As KeyPressEventArgs) End Sub Private Sub btnAddProductSale_Click(sender As Object, e As EventArgs) End Sub
  • 16. 16 Private Sub tsbtnHome_Click_1(sender As Object, e As EventArgs) Dim ManageBv As New ManageBv() Me.Close() ManageBv.Show() End Sub Private Sub tsbtnManageBv_Click(sender As Object, e As EventArgs) Dim ManageBv As New ManageBv() Me.Close() ManageBv.Show() End Sub Private Sub tsbtnPricePeople_Click(sender As Object, e As EventArgs) Dim PricePeople As New PricePeople() Me.Close() PricePeople.Show() End Sub Private Sub tsbtnReportEarn_Click(sender As Object, e As EventArgs) Dim ReportEarn As New ReportEarn() Me.Close() ReportEarn.Show() End Sub Private Sub btnSaveOrder_Click(sender As Object, e As EventArgs) End Sub Private Sub btnCancelOrder_Click(sender As Object, e As EventArgs)
  • 17. 17 End Sub ' private void txtChild_TextChanged(object sender, EventArgs e) ' { ' int number; ' if (!Int32.TryParse(txtChild.Text, out number)) ' { ' MessageBox.Show("ข้อมูลของคุณต้องเป็นตัวเลขจำนวนเต็มเท่ำนั้น", "ตรวจสอบตัวเลข", MessageBoxButtons.OK, MessageBoxIcon.Warning); ' } ' } Private Sub txtChild_KeyPress_1(sender As Object, e As KeyPressEventArgs) If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) AndAlso (e.KeyChar <> "."C) Then e.Handled = True End If ' only allow one decimal point If (e.KeyChar = "."C) AndAlso (TryCast(sender, TextBox).Text.IndexOf("."C) > -1) Then e.Handled = True End If End Sub Private Sub chkFined_CheckedChanged(sender As Object, e As EventArgs) If chkFined.Checked Then txtAmountFined.Enabled = True txtAmountFined.Focus() Else txtAmountFined.Enabled = False txtAmountFined.Focus() End If
  • 18. 18 End Sub Private Sub txtChild_KeyPress_2(sender As Object, e As KeyPressEventArgs) If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) AndAlso (e.KeyChar <> "."C) Then e.Handled = True End If ' only allow one decimal point If (e.KeyChar = "."C) AndAlso (TryCast(sender, TextBox).Text.IndexOf("."C) > -1) Then e.Handled = True End If End Sub Private Sub dgvBev_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) End Sub End Class End Namespace Manage BV Imports System.Data.SqlClient Public Class ManagBv Dim flag As String Private Sub ToolStripButton3_Click(sender As Object, e As EventArgs) Me.Hide() Main.Show() End Sub Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Me.Hide() 'addOrder.Show() End Sub Private Sub ManagBv_Load(sender As Object, e As EventArgs) Handles MyBase.Load If True Then
  • 19. 19 '1.ติดต่อฐำนข้อมูล 'string conStr = "server=ASUS-PCSqlExpress;initial catalog=DBBarBQ;integrated security=true"; Dim conStr As String = "server=ISIN;initial catalog=DBBarBQ;integrated security=true" Dim connectDB As New SqlConnection(conStr) If connectDB.State = ConnectionState.Open Then connectDB.Close() End If Try 'MessageBox.Show("โอเคผ่ำน"); connectDB.Open() Catch ex As Exception MessageBox.Show("can't Database open." + ex.Message) Return End Try '2.คำสั่ง SQL BeveragesID , BeveragesName , SalePrice , Cost , UnitStock Dim strSql As String = "select BeveragesID, BeveragesName , Cost , SalePrice , UnitStock from tb_Beverages" 'คำสั่ง '3.สั่งให้ SQl ทำงำน Dim cmd As New SqlCommand(strSql, connectDB) 'ทำงำน Dim dr As SqlDataReader = cmd.ExecuteReader() 'สั่งให้ทำงำน + ดึงค่ำที่ได้มำ '3.1 ทำอะไรก็แล้วแต่ Dim dt As New DataTable() dt.Load(dr) 'เก็บสิ่งที่ได้มำ dgvEditProduct.DataSource = dt 'เอำสิ่งที่เก็บใส่ DataGridView connectDB.Close() dgvEditProduct.Columns(0).HeaderText = "เลขที่สินค้ำ" 'กำหนดชื่อหัวColum dgvEditProduct.Columns(1).HeaderText = "ชื่อเครื่องดื่ม" dgvEditProduct.Columns(2).HeaderText = "รำคำทุน" dgvEditProduct.Columns(3).HeaderText = "รำคำขำย" dgvEditProduct.Columns(4).HeaderText = "จำนวนในสต็อก" dgvEditProduct.Columns(0).Width = 100 dgvEditProduct.Columns(1).Width = 200 dgvEditProduct.Columns(2).Width = 100 dgvEditProduct.Columns(3).Width = 100 dgvEditProduct.Columns(4).Width = 120 End If End Sub Private Sub btnCancle_Click(sender As Object, e As EventArgs) Handles btnCancle.Click If True Then btnAdd.Enabled = True btnCancle.Enabled = False btnSave.Enabled = False
  • 20. 20 btnEdit.Enabled = False btnDelete.Enabled = False txtEditProductName.Enabled = False txtEditStock.Enabled = False txtEditCost.Enabled = False txtEditPrice.Enabled = False txtEditSearch.Focus() txtEditProductId.Clear() txtEditProductName.Text = "กรอกรำยละเอียด" txtEditStock.Text = "กรอกรำยละเอียด" txtEditCost.Text = "กรอกรำยละเอียด" txtEditPrice.Text = "กรอกรำยละเอียด" txtEditSearch.Text = "กรอกรำยละเอียด" loadDateToDgvEditProducts() End If End Sub Private Sub dgvEditProduct_CellMouseUp(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvEditProduct.CellMouseUp If True Then If e.RowIndex = -1 Then Return End If txtEditProductId.Text = dgvEditProduct.Rows(e.RowIndex).Cells("BeveragesID").Value.ToString() txtEditProductName.Text = dgvEditProduct.Rows(e.RowIndex).Cells("BeveragesName").Value.ToString() txtEditStock.Text = dgvEditProduct.Rows(e.RowIndex).Cells("UnitStock").Value.ToString() txtEditCost.Text = dgvEditProduct.Rows(e.RowIndex).Cells("Cost").Value.ToString() txtEditPrice.Text = dgvEditProduct.Rows(e.RowIndex).Cells("SalePrice").Value.ToString() txtEditStock.Focus() btnAdd.Enabled = False btnCancle.Enabled = True btnEdit.Enabled = True btnDelete.Enabled = True End If End Sub Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click If True Then flag = "Add" txtEditStock.Clear() txtEditPrice.Clear() txtEditProductName.Clear() txtEditProductId.Clear() txtEditCost.Clear()
  • 21. 21 btnAdd.Enabled = False btnCancle.Enabled = True btnSave.Enabled = True txtEditProductName.Enabled = True txtEditProductName.Focus() txtEditStock.Enabled = True txtEditCost.Enabled = True txtEditPrice.Enabled = True '1.ติดต่อฐำนข้อมูล Dim conStr As String = "server=ISIN;initial catalog=DBBarBQ;integrated security=true" Dim connectDB As New SqlConnection(conStr) If connectDB.State = ConnectionState.Open Then connectDB.Close() End If Try 'MessageBox.Show("โอเคผ่ำน"); connectDB.Open() Catch ex As Exception MessageBox.Show("can't Database open." + ex.Message) Return End Try '2.คำสั่ง SQL Dim strSql As String = "select top 1 BeveragesID from tb_Beverages order by BeveragesID DESC" '3.สั่งให้ SQl ทำงำน Dim cmd As New SqlCommand(strSql, connectDB) Dim dr As SqlDataReader = cmd.ExecuteReader() '3.1 ทำอะไรก็แล้วแต่ If dr.Read() Then 'กรณีที่มีรหัสอยู่แล้ว Dim oldwaID As String = dr("BeveragesID").ToString() Dim newWaId As Integer = Convert.ToInt16(oldwaID.Substring(3)) + 1 'oldwaID เอำมำsub txtEditProductId.Text = "wa" + newWaId.ToString("000") Else 'กรณีที่ไม่มีรหัสสินค้ำเครื่องดื่ม txtEditProductId.Text = "wa001" End If '4.ยกเลิกติดต่อ connectDB.Close() End If End Sub
  • 22. 22 Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click If txtEditProductName.Text = "" Then MessageBox.Show("กรุณำกรอกชื่อสินค้ำ/เครื่องดื่ม") ElseIf txtEditStock.Text = "" Then MessageBox.Show("กรุณำกรอกจำนวนสต๊อก") ElseIf txtEditCost.Text = "" Then MessageBox.Show("กรุณำกรอกรำคำทุน") ElseIf txtEditPrice.Text = "" Then MessageBox.Show("กรุณำกรอกรำคำขำย") ElseIf flag = "Add" Then 'MessageBox.Show("add"); '1.ติดต่อฐำนข้อมูล Dim conStr As String = "server=ISIN;initial catalog=DBBarBQ;integrated security=true" Dim connectDB As New SqlConnection(conStr) If connectDB.State = ConnectionState.Open Then connectDB.Close() End If Try 'MessageBox.Show("โอเคผ่ำน"); connectDB.Open() Catch ex As Exception MessageBox.Show("can't Database open." + ex.Message) Return End Try '2. Sql statement BeveragesID, BeveragesName , Cost , SalePrice , UnitStock Dim strSql As [String] = "Insert into tb_Beverages (BeveragesID,BeveragesName,Cost,SalePrice,UnitStock)values(" + "'" + txtEditProductId.Text + "'" + ",'" + txtEditProductName.Text + "'" + ",'" + txtEditStock.Text + "'" + ",'" + txtEditCost.Text + "'" + ",'" + txtEditPrice.Text + "'" + ")" '3. สั่ง Sql statement ทำงำน Dim cmd As New SqlCommand(strSql, connectDB) cmd.ExecuteNonQuery() '3.1 ทำอะไรก็แล้วแต่ MessageBox.Show("บันทึกหน้ำจอเรียบร้อยแล้ว") '4. Disconnect connectDB.Close() btnCancle.PerformClick() End If End Sub Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click flag = "update" btnEdit.Enabled = False btnDelete.Enabled = False btnSave.Enabled = True txtEditProductName.Enabled = True txtEditProductName.Focus()
  • 23. 23 txtEditStock.Enabled = True txtEditCost.Enabled = True txtEditPrice.Enabled = True End Sub Private Sub loadDateToDgvEditProducts() End Sub Private Sub ToolStripButton1_Click_1(sender As Object, e As EventArgs) Handles ToolStripButton1.Click Me.Hide() Main.Show() End Sub Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click Me.Hide() End Sub Private Sub ToolStripButton4_Click(sender As Object, e As EventArgs) Handles ToolStripButton4.Click Me.Hide() PricePeople.Show() End Sub Private Sub ToolStripButton5_Click_1(sender As Object, e As EventArgs) Handles ToolStripButton5.Click Me.Hide() ReportEarn.Show() End Sub Private Sub txtEditStock_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtEditStock.KeyPress If e.KeyChar.ToString = "." And txtEditStock.Text.Contains(".") Then e.Handled = True Exit Sub End If Dim regex As String = "^[0-9.rntbs]+$" Dim r As New System.Text.RegularExpressions.Regex(regex) If r.IsMatch(e.KeyChar.ToString()) Then e.Handled = False Else e.Handled = True End If End Sub Private Sub txtEditCost_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtEditCost.KeyPress If e.KeyChar.ToString = "." And txtEditCost.Text.Contains(".") Then e.Handled = True Exit Sub End If
  • 24. 24 Dim regex As String = "^[0-9.rntbs]+$" Dim r As New System.Text.RegularExpressions.Regex(regex) If r.IsMatch(e.KeyChar.ToString()) Then e.Handled = False Else e.Handled = True End If End Sub Private Sub txtEditPrice_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtEditPrice.KeyPress If e.KeyChar.ToString = "." And txtEditPrice.Text.Contains(".") Then e.Handled = True Exit Sub End If Dim regex As String = "^[0-9.rntbs]+$" Dim r As New System.Text.RegularExpressions.Regex(regex) If r.IsMatch(e.KeyChar.ToString()) Then e.Handled = False Else e.Handled = True End If End Sub Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click MessageBox.Show("ยืนยันกำรลบ") btnDelete.Enabled = False btnCancle.Enabled = True If MessageBox.Show("ต้องกำรลบหรือไม่", "ยืนยัน", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then '1.ติดต่อฐำนข้อมูล 'string conStr = "server=ASUS-PCSqlExpress;initial catalog=DBBarBQ;integrated security=true"; Dim conStr As String = "server=ISIN;initial catalog=DBBarBQ;integrated security=true" Dim connectDB As New SqlConnection(conStr) If connectDB.State = ConnectionState.Open Then connectDB.Close() End If Try 'MessageBox.Show("โอเคผ่ำน"); connectDB.Open() Catch ex As Exception MessageBox.Show("can't Database open." + ex.Message) Return End Try Dim strSql As String = "delete from tb_Beverages where BeveragesID = '" + txtEditProductId.Text + "'" Dim cmd As New SqlCommand(strSql, connectDB) Dim dr As SqlDataReader = cmd.ExecuteReader()
  • 25. 25 MessageBox.Show("ลบรำยกำรเรียบร้อยแล้ว") '4. Disconnect connectDB.Close() btnDelete.Enabled = False btnCancle.Enabled = True btnDelete.Enabled = False btnCancle.Enabled = True dgvEditProduct.Refresh() End If End Sub End Class Public Class PricePeople Private Sub btnEdit_Click(sender As Object, e As EventArgs) txtAdult.Enabled = True End Sub Private Sub btnEdit2_Click(sender As Object, e As EventArgs) txtChild.Enabled = True End Sub Private Sub loadDataToPricePeople() '1.ติดต่อฐานข้อมูล Dim conStr As String = "server=Localhost;initial catalog=DBBarBQ;integrated security=true" Dim connectDB As New SqlConnection(conStr) If connectDB.State = ConnectionState.Open Then connectDB.Close() End If Try 'MessageBox.Show("โอเคผ่าน"); connectDB.Open() Catch ex As Exception MessageBox.Show("can't Database open." + ex.Message) Return End Try '2.คาสั่ง SQL (DateEdit,Child,Adult) Dim strSql As String = "select top 1 Child, Adult , DateEdit from tb_PricePerson order by DateEdit desc" 'คาสั่ง '3.สั่งให้ SQl ทางาน Dim cmd As New SqlCommand(strSql, connectDB) 'ทางาน Dim dr As SqlDataReader = cmd.ExecuteReader() 'สั่งให้ทางาน + ดึงค่าที่ได้มา '3.1 ทาอะไรก็แล้วแต่ If dr.Read() Then txtAdult.Text = dr("Child").ToString() txtChild.Text = dr("Adult").ToString()
  • 26. 26 Dim dateDr As String = dr("DateEdit").ToString() dateDr = dateDr.Substring(0, 9) 'lblDateNowPrice.Text = DateTime.Now.ToString("dd MMMM yyyy", New System.Globalization.CultureInfo("th-TH")) End If '4.ปิด connectDB.Close() txtChild.Enabled = False txtAdult.Enabled = False dtpEdit.Enabled = False End Sub Private Sub PricePeople_Load(sender As Object, e As EventArgs) Handles MyBase.Load loadDataToPricePeople() txtAdult.Enabled = False txtChild.Enabled = False End Sub Private Sub btnEditDateFinish_Click(sender As Object, e As EventArgs) dtpEdit.Enabled = True End Sub Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click Me.Hide() Main.Show() End Sub Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click Me.Hide() AddOrder.Show() End Sub Private Sub ToolStripButton3_Click(sender As Object, e As EventArgs) Handles ToolStripButton3.Click Me.Hide() ManagBv.Show() End Sub Private Sub ToolStripButton5_Click(sender As Object, e As EventArgs) Handles ToolStripButton5.Click Me.Hide() ReportEarn.Show() End Sub Private Sub btnSavePricePeople_Click(sender As Object, e As EventArgs) Handles btnSavePricePeople.Click 'MessageBox.Show(txtAdult.Text); If Convert.ToInt16(txtAdult.Text) > 999 Then MessageBox.Show("กรุณาระบุค่าบุฟเฟ่ต์ไม่เกิน 999 บาท") txtAdult.Focus() ElseIf Convert.ToInt16(txtChild.Text) > 999 Then MessageBox.Show("กรุณาระบุค่าบุฟเฟ่ต์ไม่เกิน 999 บาท")
  • 27. 27 txtChild.Focus() Else '1.ติดต่อฐานข้อมูล 'string conStr = "server=ASUS-PCSqlExpress;initial catalog=DBBarBQ;integrated security=true"; Dim conStr As String = "server=Localhost;initial catalog=DBBarBQ;integrated security=true" Dim connectDB As New SqlConnection(conStr) If connectDB.State = ConnectionState.Open Then connectDB.Close() End If Try 'MessageBox.Show("โอเคผ่าน"); connectDB.Open() Catch ex As Exception MessageBox.Show("can't Database open." + ex.Message) Return End Try 'String dateS = dtpFinish.Value.Date.ToShortDateString(); Dim dateEdit As String = DateTime.Now.ToString("yyyy-MM-dd " + "hh:mm:ss.fff") Dim YYYYF As String = (Convert.ToInt16(dtpEdit.Value.[Date].ToString("yyyy")) - 543).ToString("0000") 'String dateF = dtpEdit.Value.Date.ToString(YYYYF + "-MM-dd " + "hh:mm:ss.fff"); Dim yyyy As Integer = Convert.ToInt16(dtpEdit.Value.[Date].ToString("yyyy")) Dim MM As Integer = Convert.ToInt16(dtpEdit.Value.[Date].ToString("MM")) Dim dd As Integer = Convert.ToInt16(dtpEdit.Value.[Date].ToString("dd")) 'MessageBox.Show(a.ToString() + b.ToString()); 'yyyyF<S 'MMF<S 'ddF<S If yyyy < Convert.ToInt16(DateTime.Now.ToString("yyyy")) Then MessageBox.Show("กรุณาตรวจสอบปี") ElseIf yyyy = Convert.ToInt16(DateTime.Now.ToString("yyyy")) AndAlso MM < Convert.ToInt16(DateTime.Now.ToString("MM")) Then MessageBox.Show("กรุณาตรวจสอบเดือน") ElseIf yyyy = Convert.ToInt16(DateTime.Now.ToString("yyyy")) AndAlso MM = Convert.ToInt16(DateTime.Now.ToString("MM")) AndAlso dd < Convert.ToInt16(DateTime.Now.ToString("dd")) Then MessageBox.Show("กรุณาตรวจสอบวัน") Else '2. Sql statement //ลงตาราง tb_PricePerson (DateStart,Child,Adult,Datefinish) Dim strSql As [String] = (Convert.ToString("Insert into tb_PricePerson (DateEdit,Adult,Child)values(" + " '") & dateEdit) + "'" + ",'" + txtChild.Text + "'" + ",'" + txtAdult.Text + "'" + ")" '3. สั่ง Sql statement ทางาน Dim cmd As New SqlCommand(strSql, connectDB) cmd.ExecuteNonQuery() '3.1 MessageBox.Show("บันทึกหน้าจอเรียบร้อยแล้ว") End If '4.close DB connectDB.Close() loadDataToPricePeople() End If
  • 28. 28 End Sub 'MsgBox(txtAdult.Text & " " & txtChild.Text & " " & dtpFinish.Text) 'If True Then ' '1.ติดต่อฐานข้อมูล ' 'string conStr = "server=ISIN;initial catalog=DBBarBQ;integrated security=true"; ' Dim conStr As String = "server=Localhost;initial catalog=DBBarBQ;integrated security=true" ' Dim connectDB As New SqlConnection(conStr) ' If connectDB.State = ConnectionState.Open Then ' connectDB.Close() ' End If ' Try ' 'MessageBox.Show("โอเคผ่าน"); ' connectDB.Open() ' Catch ex As Exception ' MessageBox.Show("can't Database open." + ex.Message) ' Return ' End Try ' 'string dateS = dtpFinish.Value.Date.ToShortDateString(); ' Dim dateS As String = DateTime.Now.ToString("yyyy-MM-dd " + "hh:mm:ss.fff") ' Dim YYYYF As String = (Convert.ToInt16(dtpFinish.Value.[Date].ToString("yyyy")) - 543).ToString("0000") ' Dim dateF As String = dtpFinish.Value.[Date].ToString((YYYYF & Convert.ToString("-MM-dd ")) + "hh:mm:ss.fff") ' Dim yyyy As Integer = Convert.ToInt16(dtpFinish.Value.[Date].ToString("yyyy")) ' Dim MM As Integer = Convert.ToInt16(dtpFinish.Value.[Date].ToString("MM")) ' Dim dd As Integer = Convert.ToInt16(dtpFinish.Value.[Date].ToString("dd")) ' 'MessageBox.Show(a.ToString() + b.ToString()); ' 'yyyyF<S ' 'MMF<S ' 'ddF<S ' If yyyy < Convert.ToInt16(DateTime.Now.ToString("yyyy")) Then ' MessageBox.Show("กรุณาตรวจสอบปี") ' ElseIf yyyy = Convert.ToInt16(DateTime.Now.ToString("yyyy")) AndAlso MM < Convert.ToInt16(DateTime.Now.ToString("MM")) Then ' MessageBox.Show("กรุณาตรวจสอบเดือน") ' ElseIf yyyy = Convert.ToInt16(DateTime.Now.ToString("yyyy")) AndAlso MM = Convert.ToInt16(DateTime.Now.ToString("MM")) AndAlso dd < Convert.ToInt16(DateTime.Now.ToString("dd")) Then ' MessageBox.Show("กรุณาตรวจสอบวัน") ' Else ' '2. Sql statement //ลงตาราง tb_PricePerson (DateStart,Child,Adult,Datefinish) ' '+ ",'" + txtAdult.Text + "'" ' '+ ", 2558-09-04 00:00:00 " ' Dim strSql As [String] = (Convert.ToString((Convert.ToString("Insert into tb_PricePerson (DateStart,Adult,Child,Datefinish)values(" + " '") & dateS) + "'" + ",'" + txtAdult.Text + "'" + ",'" + txtChild.Text + "'" + ",'") & dateF) + "'" + ")" ' '3. สั่ง Sql statement ทางาน ' Dim cmd As New SqlCommand(strSql, connectDB) ' cmd.ExecuteNonQuery() ' '3.1
  • 29. 29 ' MessageBox.Show("บันทึกหน้าจอเรียบร้อยแล้ว") ' End If ' '4.close DB ' connectDB.Close() ' loadDataToPricePeople() 'End If Private Sub btnEditAdult_Click(sender As Object, e As EventArgs) txtAdult.Enabled = True txtAdult.Focus() End Sub Private Sub btnEditChild_Click(sender As Object, e As EventArgs) txtChild.Enabled = True txtChild.Focus() End Sub Private Sub Label6_Click(sender As Object, e As EventArgs) Handles Label6.Click End Sub Private Sub btnEditDateFinish_Click_1(sender As Object, e As EventArgs) Handles btnEditDateFinish.Click txtAdult.Enabled = True txtAdult.Focus() txtChild.Enabled = True dtpEdit.Enabled = True End Sub Private Sub txtAdult_KeyDown(sender As Object, e As KeyEventArgs) Handles txtAdult.KeyDown If e.KeyCode = Keys.Enter Then txtChild.Focus() End If End Sub Private Sub txtChild_KeyDown(sender As Object, e As KeyEventArgs) Handles txtChild.KeyDown If e.KeyCode = Keys.Enter Then dtpEdit.Focus() End If End Sub End Class
  • 30. 30 โค๊ด combobox ดึงข้อมูลออกมำ จำก Db Dim strConnString As String strConnString = "Server=localhost;User Id=root; Password=root; Database=mydatabase; Pooling=false" objConn = New MySqlConnection(strConnString) objConn.Open() Dim sqlGeo As String = "SELECT geo_name FROM geography" Dim daGeo As New MySqlDataAdapter(sqlGeo, con) Dim dtGeo As New DataTable daGeo.Fill(dtGeo) With cmbGeo .DataSource = dtGeo .DisplayMember = dtGeo.Columns.Item("geo_name").ColumnName End With ต้องกำร ให้ลบแถวที่เรำเลือกไว้ ลบ โดย ใช้ปุ่ม del ปกติ ให้มีข้อควำมเตือนและสำมำรถลบได้ปกตำมที่ defalut niras srihemthong: Private Sub DataGridView1_KeyDown(ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyEventArgs) _ Handles DataGridView1.KeyDown Dim CurRow As Integer CurRow = Me.DataGridView1.CurrentRow.Index If e.KeyCode = Keys.Delete Then If Me.DataGridView1.Rows.Count <> 1 Then Dim Result As MsgBoxResult Result = MessageBox.Show("ต้องกำรลบข้อมูลแถวนี้หรือไม่", "ยืนยัน", MessageBoxButtons.YesNo, _ MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
  • 31. 31 If Result = MsgBoxResult.Yes Then Me.DataGridView1.Rows.RemoveAt(CurRow) End If End If End If End Sub ผมว่ำผูกข้อมูลโดยกำรเขียนโค้ดจะดีกว่ำในกรณีต้องกำร refresh ข้อมูลใหม่บ่อยหรือมีกำรใช้งำนร่วมกันหลำย ๆ ฟอร์ม ถ้ำจะอธิบำยก็คงต้องเริ่มตั้งแต่กำร เขียนโค้ดในกำรผูก ข้อมูลตั้งแต่เริ่มแรกเลยไม่ยำกครับลองแกะดูครับ ผมก็อำศัยวิธีเดียวกับคุณนั้นแหละ เพรำะว่ำหนังสือไทยไม่มีเลย ก็ต้องไปหำอ่ำนตำมเว็บเมืองนอก ผมจะเขียนแบบนี้ครับ Imports System.Data.OleDb 'เรียกใช้เฟรมเวิร์ก Public Class form1 Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _ Windows.Forms.Application.StartupPath & "databaseMyDataBase.mdb;Jet OLEDB:Database Password=1234;" 'กำหนด พำร์ทของฐำนข้อมูลครับ ในที่นี้เป็นฐำนข้อมูล Access ชื่อว่ำ MyDataBase.mdb password 1234 ถ้ำมีกำรตั้ง password ใน access คำสั่ง StartupPath เป็น คำสั่งระบุว่ำ ฐำนข้อมูลนี้อยู่ภำยในโฟลเดอร์เดียวกันกับโปรแกรม และอยู่ภำยใน ซับโฟล์เดอร์ ที่ชื่อว่ำ database Dim Conn As New OleDbConnection(strConn) ' เรียกใช้คำสั่ง ติดต่อฐำนข้อมูล Dim ds As New DataSet 'กำหนดตัวแปรเป็นแบบดำต้ำเซ็ท ตัวแปรนี้แหละครับจะเป็นตัว refresh ข้อมูล Private Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim StrSql As String StrSql = "SELECT * FROM MyTable " 'คำสั่ง SQL Dim da As OleDbDataAdapter 'ตัวแปรนี้ก็คือ DataAdapter ที่คุณใช้ใน Tool ครับ da = New OleDbDataAdapter(StrSql, Conn) 'เก็บข้อมูลจำกกำรเรียกใช้คำสั่ง SQL เข้ำมำใน DataAdapter da.Fill(ds, "MyData") 'นำเข้ำมูล จำก DataAdapter มำเก็บไว้ ในดำต้ำเซ็ทที่ชื่อ ds ครับ ds เป็นดำต้ำเซ็ทที่ใช้ในกำรพักข้อมูลก่อนส่งเข้ำไปแสดงที่ดำต้ำกริด Mydata เป็นชื่อที่ตั้งเพื่อสื่อควำมหมำยแทนข้อมูลในดำต้ำเซ็ทครับ Me.DataGridView1.DataSource = ds.Tables("MyData") 'นำข้อมูลที่ได้มำแสดงที่ดำต้ำกริดครับ End Sub
  • 32. 32 End Class ต่อไปก็จะเป็นกำร รีเฟรชข้อมูลครับ ใช้คำสั่งนี้ If ds.Tables.Contains("MyData") Then 'ก็จะตรวจสอบ ข้อมูลค้ำงอยู่ใน ดำต้ำเซ็ทไหม ถ้ำมีค้ำงอยู่ใน รีมูฟ ออกก่อน ds.Tables.Remove("MyData") End If ก็เป็นกำรตัดกำรผูกข้อมูลกับฐำนข้อมูล ถ้ำจะมีกำรดึงข้อมูลขึ้นมำอีกก็ทำตำมโค้ดข้ำงบนเหมือนเดิม คุณต้องทำควำมเข้ำใจกับ ตัวแปร ds หรือ ดำต้ำเซ็ทก่อนนะครับ ดำต้ำเซ็ท เป็นตำรำงข้อมูลในรูปแบบ temporary ดูง่ำย ๆ เหมือนไฟล์เอ็กเซลที่เก็บไว้ในหน่วยควำมจำ ดำต้ำเซ็ทสำมำรถมีได้หลำยตำรำงเหมือนกับเอ็กเซลก็สำมำรถมีได้หลำย sheet คุณ สำมำรถ fill เข้ำดำต้ำเซ็ทได้หลำยตำรำงก็ได้ เช่น da.Fill(ds, "MyData") หรือ da.Fill(ds, "MyData1 ") , da.Fill(ds, "MyDataN") จำก da หรือ DataAdapter ตัว เดียวกันได้ Public Class frmMain 'By http://www.thaicreate.com (mr.win)' Private Sub btnHome_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHome.Click Me.Hide() Dim f As New frmHome f.Show() End Sub Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click If MessageBox.Show("Are you sure to exit?", "Confirm.", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) = DialogResult.Yes Then Application.Exit() End If End Sub End Class Imports System.Data Imports System.Data.SqlServerCe Imports System.Data.SqlTypes
  • 33. 33 Imports System.Drawing Imports System.ComponentModel Imports System.Windows.Forms Public Class frmHome 'By http://www.thaicreate.com (mr.win)' Private Sub frmHome_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load BindDataGrid() End Sub Private Sub BindDataGrid() Dim myConnection As SqlCeConnection Dim dt As New DataTable Dim Adapter As SqlCeDataAdapter 'myConnection = New SqlCeConnection("Data Source =" + (System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase ) + "Database1.sdf;")) myConnection = New SqlCeConnection("Data Source=C:WindowsFormsApplicationWindowsFormsApplicationDatabase1.sdf;") myConnection.Open() Dim myCommand As SqlCeCommand = myConnection.CreateCommand() myCommand.CommandText = "SELECT [id], [name], [email] FROM [mytable]" myCommand.CommandType = CommandType.Text Adapter = New SqlCeDataAdapter(myCommand) Adapter.Fill(dt) myConnection.Close() Me.dgName.DataSource = dt Me.dgName.Columns.Clear()
  • 34. 34 Dim column As DataGridViewTextBoxColumn column = New DataGridViewTextBoxColumn() column.DataPropertyName = "id" column.HeaderText = "ID" column.Width = 50 Me.dgName.Columns.Add(column) column = New DataGridViewTextBoxColumn() column.DataPropertyName = "name" column.HeaderText = "Name" column.Width = 100 Me.dgName.Columns.Add(column) column = New DataGridViewTextBoxColumn() column.DataPropertyName = "email" column.HeaderText = "Email" column.Width = 150 Me.dgName.Columns.Add(column) dt = Nothing End Sub Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click Me.Hide() Dim f As New frmAdd f.Show() End Sub
  • 35. 35 Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click Me.Hide() Dim f As New frmEdit() f._strID = Me.dgName(0, Me.dgName.CurrentCell.RowIndex).Value.ToString() f.Show() End Sub Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDel.Click If MessageBox.Show("Are you sure to delete?", "Confirm.", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) = DialogResult.Yes Then Dim strID As String = Me.dgName(0, Me.dgName.CurrentCell.RowIndex).Value.ToString() Dim myConnection As SqlCeConnection 'myConnection = New SqlCeConnection("Data Source =" + (System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase ) + "Database1.sdf;")) myConnection = New SqlCeConnection("Data Source=C:WindowsFormsApplicationWindowsFormsApplicationDatabase1.sdf;") myConnection.Open() Dim myCommand As SqlCeCommand = myConnection.CreateCommand() myCommand.CommandText = "DELETE FROM [mytable] WHERE id = '" & strID & "'" myCommand.CommandType = CommandType.Text myCommand.ExecuteNonQuery() myConnection.Close() MessageBox.Show("Delete Successfully") BindDataGrid() End If End Sub Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click Me.Hide() Dim f As New frmMain
  • 36. 36 f.Show() End Sub End Class Imports System.Data Imports System.Data.SqlServerCe Imports System.Data.SqlTypes Imports System.Drawing Imports System.ComponentModel Imports System.Windows.Forms Public Class frmAdd 'By http://www.thaicreate.com (mr.win)' Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click If Me.txtName.Text = "" Then MessageBox.Show("Please input (Name)") Me.txtName.Focus() Exit Sub End If If Me.txtEmail.Text = "" Then MessageBox.Show("Please input (Email)") Me.txtEmail.Focus() Exit Sub End If Dim myConnection As SqlCeConnection 'myConnection = New SqlCeConnection("Data Source =" + (System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase ) + "Database1.sdf;"))
  • 37. 37 myConnection = New SqlCeConnection("Data Source=C:WindowsFormsApplicationWindowsFormsApplicationDatabase1.sdf;") myConnection.Open() Dim myCommand As SqlCeCommand = myConnection.CreateCommand() myCommand.CommandText = "INSERT INTO [mytable] ([name], [email]) VALUES " & _ " ('" & Me.txtName.Text & "','" & Me.txtEmail.Text & "' ) " myCommand.CommandType = CommandType.Text myCommand.ExecuteNonQuery() myConnection.Close() MessageBox.Show("Save Successfully.") Me.Hide() Dim f As New frmHome f.Show() End Sub Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click Me.Hide() Dim f As New frmHome f.Show() End Sub End Class Imports System.Data Imports System.Data.SqlServerCe Imports System.Data.SqlTypes Imports System.Drawing Imports System.ComponentModel Imports System.Windows.Forms Public Class frmEdit
  • 38. 38 'By http://www.thaicreate.com (mr.win)' Dim strID As String = "" Public Property _strID() As String Get Return strID End Get Set(ByVal value As String) strID = value End Set End Property Private Sub frmEdit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim myConnection As SqlCeConnection Dim dt As New DataTable Dim Adapter As SqlCeDataAdapter 'myConnection = New SqlCeConnection("Data Source =" + (System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase ) + "Database1.sdf;")) myConnection = New SqlCeConnection("Data Source=C:WindowsFormsApplicationWindowsFormsApplicationDatabase1.sdf;") myConnection.Open() Dim myCommand As SqlCeCommand = myConnection.CreateCommand() myCommand.CommandText = "SELECT [id], [name], [email] FROM [mytable] WHERE id = '" & strID & "' " myCommand.CommandType = CommandType.Text Adapter = New SqlCeDataAdapter(myCommand) Adapter.Fill(dt) myConnection.Close() If dt.Rows.Count > 0 Then Me.txtName.Text = dt.Rows(0)("name")
  • 39. 39 Me.txtEmail.Text = dt.Rows(0)("email") End If dt = Nothing End Sub Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click If Me.txtName.Text = "" Then MessageBox.Show("Please input (Name)") Me.txtName.Focus() Exit Sub End If If Me.txtEmail.Text = "" Then MessageBox.Show("Please input (Email)") Me.txtEmail.Focus() Exit Sub End If Dim myConnection As SqlCeConnection 'myConnection = New SqlCeConnection("Data Source =" + (System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase ) + "Database1.sdf;")) myConnection = New SqlCeConnection("Data Source=C:WindowsFormsApplicationWindowsFormsApplicationDatabase1.sdf;") myConnection.Open() Dim myCommand As SqlCeCommand = myConnection.CreateCommand() myCommand.CommandText = "UPDATE [mytable] SET " & _ " [name] = '" & Me.txtName.Text & "', [email] = '" & Me.txtEmail.Text & "' " & _ " WHERE id = '" & strID & "' " myCommand.CommandType = CommandType.Text myCommand.ExecuteNonQuery()
  • 40. 40 myConnection.Close() MessageBox.Show("Update Successfully") Me.Hide() Dim f As New frmHome f.Show() End Sub Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click Me.Hide() Dim f As New frmHome f.Show() End Sub End Class