17 ธันวาคม 2553

VB.Net One Table Data Entry

ตัวอย่าง การเขียนโปรแกรมป้อนข้อมูลในลักษณะตารางเดียว ซึ่งมีทั้งการสอบถามข้อมูล การแสดงข้อมูล การเพิ่มข้อมูล การลบข้อมูล การแก้ไขข้อมูล และการลบข้อมูล อยู่ในหน้าจอเดียวกัน ตามตัวอย่างในภาพ





















ก่อนอื่นสร้างโปรเจกต์ใหม่ โดยตั้งชื่อว่า myAPP





สำหรับวิธีการใส่โค้ดภายใต้ Form1.Designer.vb ให้ทำดังนี้
(ทำเพื่อเราไม่ต้องมาลากวางคอนโทรลต่าง ๆ ตามรูปด้านบน)






















 ที่ Solution Explorer
      - คลิกที่ปุ่ม หมายเลข 1 Show All File
      - คลิกที่หมายเลข 2 เพื่อแสดงไฟล์ทั้งหมดของ Form1
      - ดับเบิ้ลคลิกที่ไฟล์หมายเลข 3 เพื่อเปิด Source Code ขึ้นมา

  จากนั้นนำโค้ดด้านล่างนี้ไปแทนที่โค้ดของเดิม

Source Code -> Form1.Designer.vb

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form

'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub

'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.txtStudent_ID = New System.Windows.Forms.TextBox()
Me.txtFirstName = New System.Windows.Forms.TextBox()
Me.txtLastName = New System.Windows.Forms.TextBox()
Me.Label1 = New System.Windows.Forms.Label()
Me.Label2 = New System.Windows.Forms.Label()
Me.Label3 = New System.Windows.Forms.Label()
Me.SplitContainer1 = New System.Windows.Forms.SplitContainer()
Me.Label4 = New System.Windows.Forms.Label()
Me.txtSearch = New System.Windows.Forms.TextBox()
Me.dg = New System.Windows.Forms.DataGridView()
Me.btnLast = New System.Windows.Forms.Button()
Me.btnFirst = New System.Windows.Forms.Button()
Me.btnDisplay = New System.Windows.Forms.Button()
Me.btnPrevious = New System.Windows.Forms.Button()
Me.btnNext = New System.Windows.Forms.Button()
Me.btnNew = New System.Windows.Forms.Button()
Me.btnDelete = New System.Windows.Forms.Button()
Me.btnEdit = New System.Windows.Forms.Button()
Me.btnSave = New System.Windows.Forms.Button()
Me.btnCancel = New System.Windows.Forms.Button()
CType(Me.SplitContainer1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SplitContainer1.Panel1.SuspendLayout()
Me.SplitContainer1.Panel2.SuspendLayout()
Me.SplitContainer1.SuspendLayout()
CType(Me.dg, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()

'
'txtStudent_ID
'
Me.txtStudent_ID.Location = New System.Drawing.Point(100, 25)
Me.txtStudent_ID.Name = "txtStudent_ID"
Me.txtStudent_ID.Size = New System.Drawing.Size(150, 20)
Me.txtStudent_ID.TabIndex = 1

'
'txtFirstName
'
Me.txtFirstName.Location = New System.Drawing.Point(100, 52)
Me.txtFirstName.Name = "txtFirstName"
Me.txtFirstName.Size = New System.Drawing.Size(236, 20)
Me.txtFirstName.TabIndex = 2

'
'txtLastName
'
Me.txtLastName.Location = New System.Drawing.Point(100, 79)
Me.txtLastName.Name = "txtLastName"
Me.txtLastName.Size = New System.Drawing.Size(236, 20)
Me.txtLastName.TabIndex = 3

'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(36, 28)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(58, 13)
Me.Label1.TabIndex = 4
Me.Label1.Text = "Student ID"

'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Location = New System.Drawing.Point(36, 55)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(57, 13)
Me.Label2.TabIndex = 5
Me.Label2.Text = "First Name"

'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.Location = New System.Drawing.Point(35, 82)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(58, 13)
Me.Label3.TabIndex = 6
Me.Label3.Text = "Last Name"

'
'SplitContainer1
'
Me.SplitContainer1.Location = New System.Drawing.Point(13, 13)
Me.SplitContainer1.Name = "SplitContainer1"
Me.SplitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal

'
'SplitContainer1.Panel1
'
Me.SplitContainer1.Panel1.BackColor = System.Drawing.SystemColors.ActiveCaption
Me.SplitContainer1.Panel1.Controls.Add(Me.Label4)
Me.SplitContainer1.Panel1.Controls.Add(Me.txtSearch)
Me.SplitContainer1.Panel1.Controls.Add(Me.dg)
Me.SplitContainer1.Panel1.Controls.Add(Me.btnLast)
Me.SplitContainer1.Panel1.Controls.Add(Me.btnFirst)
Me.SplitContainer1.Panel1.Controls.Add(Me.btnDisplay)
Me.SplitContainer1.Panel1.Controls.Add(Me.btnPrevious)
Me.SplitContainer1.Panel1.Controls.Add(Me.btnNext)

'
'SplitContainer1.Panel2
'
Me.SplitContainer1.Panel2.BackColor = System.Drawing.SystemColors.ActiveCaption
Me.SplitContainer1.Panel2.Controls.Add(Me.Label3)
Me.SplitContainer1.Panel2.Controls.Add(Me.txtLastName)
Me.SplitContainer1.Panel2.Controls.Add(Me.Label2)
Me.SplitContainer1.Panel2.Controls.Add(Me.txtStudent_ID)
Me.SplitContainer1.Panel2.Controls.Add(Me.Label1)
Me.SplitContainer1.Panel2.Controls.Add(Me.txtFirstName)
Me.SplitContainer1.Size = New System.Drawing.Size(458, 365)
Me.SplitContainer1.SplitterDistance = 225
Me.SplitContainer1.TabIndex = 0

'
'Label4
'
Me.Label4.AutoSize = True
Me.Label4.Location = New System.Drawing.Point(15, 12)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(58, 13)
Me.Label4.TabIndex = 13
Me.Label4.Text = "Student ID"

'
'txtSearch
'
Me.txtSearch.Location = New System.Drawing.Point(78, 9)
Me.txtSearch.Name = "txtSearch"
Me.txtSearch.Size = New System.Drawing.Size(334, 20)
Me.txtSearch.TabIndex = 0

'
'dg
'
Me.dg.AllowUserToAddRows = False
Me.dg.AllowUserToDeleteRows = False
Me.dg.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.dg.Location = New System.Drawing.Point(4, 35)
Me.dg.Name = "dg"
Me.dg.ReadOnly = True
Me.dg.Size = New System.Drawing.Size(451, 149)
Me.dg.TabIndex = 1

'
'btnLast
'
Me.btnLast.Location = New System.Drawing.Point(311, 190)
Me.btnLast.Name = "btnLast"
Me.btnLast.Size = New System.Drawing.Size(60, 23)
Me.btnLast.TabIndex = 6
Me.btnLast.Text = "Last"
Me.btnLast.UseVisualStyleBackColor = True

'
'btnFirst
'
Me.btnFirst.Location = New System.Drawing.Point(113, 190)
Me.btnFirst.Name = "btnFirst"
Me.btnFirst.Size = New System.Drawing.Size(60, 23)
Me.btnFirst.TabIndex = 3
Me.btnFirst.Text = "First"
Me.btnFirst.UseVisualStyleBackColor = True

'
'btnDisplay
'
Me.btnDisplay.Location = New System.Drawing.Point(4, 190)
Me.btnDisplay.Name = "btnDisplay"
Me.btnDisplay.Size = New System.Drawing.Size(58, 23)
Me.btnDisplay.TabIndex = 2
Me.btnDisplay.Text = "Refresh"
Me.btnDisplay.UseVisualStyleBackColor = True

'
'btnPrevious
'
Me.btnPrevious.Location = New System.Drawing.Point(179, 190)
Me.btnPrevious.Name = "btnPrevious"
Me.btnPrevious.Size = New System.Drawing.Size(60, 23)
Me.btnPrevious.TabIndex = 4
Me.btnPrevious.Text = "Previous"
Me.btnPrevious.UseVisualStyleBackColor = True

'
'btnNext
'
Me.btnNext.Location = New System.Drawing.Point(245, 190)
Me.btnNext.Name = "btnNext"
Me.btnNext.Size = New System.Drawing.Size(60, 23)
Me.btnNext.TabIndex = 5
Me.btnNext.Text = "Next"
Me.btnNext.UseVisualStyleBackColor = True

'
'btnNew
'
Me.btnNew.Location = New System.Drawing.Point(17, 384)
Me.btnNew.Name = "btnNew"
Me.btnNew.Size = New System.Drawing.Size(75, 23)
Me.btnNew.TabIndex = 13
Me.btnNew.Text = "New"
Me.btnNew.UseVisualStyleBackColor = True

'
'btnDelete
'
Me.btnDelete.Location = New System.Drawing.Point(177, 384)
Me.btnDelete.Name = "btnDelete"
Me.btnDelete.Size = New System.Drawing.Size(75, 23)
Me.btnDelete.TabIndex = 15
Me.btnDelete.Text = "Delete"
Me.btnDelete.UseVisualStyleBackColor = True

'
'btnEdit
'
Me.btnEdit.Location = New System.Drawing.Point(98, 384)
Me.btnEdit.Name = "btnEdit"
Me.btnEdit.Size = New System.Drawing.Size(75, 23)
Me.btnEdit.TabIndex = 18
Me.btnEdit.Text = "Edit"
Me.btnEdit.UseVisualStyleBackColor = True

'
'btnSave
'
Me.btnSave.Location = New System.Drawing.Point(312, 384)
Me.btnSave.Name = "btnSave"
Me.btnSave.Size = New System.Drawing.Size(75, 23)
Me.btnSave.TabIndex = 15
Me.btnSave.Text = "Save"
Me.btnSave.UseVisualStyleBackColor = True

'
'btnCancel
'
Me.btnCancel.Location = New System.Drawing.Point(393, 384)
Me.btnCancel.Name = "btnCancel"
Me.btnCancel.Size = New System.Drawing.Size(75, 23)
Me.btnCancel.TabIndex = 16
Me.btnCancel.Text = "Cencel"
Me.btnCancel.UseVisualStyleBackColor = True

'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(487, 417)
Me.Controls.Add(Me.btnCancel)
Me.Controls.Add(Me.btnEdit)
Me.Controls.Add(Me.btnSave)
Me.Controls.Add(Me.btnDelete)
Me.Controls.Add(Me.btnNew)
Me.Controls.Add(Me.SplitContainer1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.SplitContainer1.Panel1.ResumeLayout(False)
Me.SplitContainer1.Panel1.PerformLayout()
Me.SplitContainer1.Panel2.ResumeLayout(False)
Me.SplitContainer1.Panel2.PerformLayout()
CType(Me.SplitContainer1, System.ComponentModel.ISupportInitialize).EndInit()
Me.SplitContainer1.ResumeLayout(False)
CType(Me.dg, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)

End Sub

Friend WithEvents txtStudent_ID As System.Windows.Forms.TextBox
Friend WithEvents txtFirstName As System.Windows.Forms.TextBox
Friend WithEvents txtLastName As System.Windows.Forms.TextBox
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Label3 As System.Windows.Forms.Label
Friend WithEvents SplitContainer1 As System.Windows.Forms.SplitContainer
Friend WithEvents dg As System.Windows.Forms.DataGridView
Friend WithEvents btnDisplay As System.Windows.Forms.Button
Friend WithEvents btnFirst As System.Windows.Forms.Button
Friend WithEvents btnPrevious As System.Windows.Forms.Button
Friend WithEvents btnNext As System.Windows.Forms.Button
Friend WithEvents btnLast As System.Windows.Forms.Button
Friend WithEvents btnNew As System.Windows.Forms.Button
Friend WithEvents txtSearch As System.Windows.Forms.TextBox
Friend WithEvents btnDelete As System.Windows.Forms.Button
Friend WithEvents btnEdit As System.Windows.Forms.Button
Friend WithEvents Label4 As System.Windows.Forms.Label
Friend WithEvents btnSave As System.Windows.Forms.Button
Friend WithEvents btnCancel As System.Windows.Forms.Button

End Class



เขียนคำสั่งภายใต้ไฟล์ Form1.vb
จากนั้นให้ไปดับเบิ้ลคลิกที่ฟอร์ม Form1.vb เพื่อเขียนโค้ดคำสั่งภาษา VB
ให้นำคำสั่งด้านล่างไปแทนคำสั่ง VB เดิมได้เลย

Source Code -> Form1.vb

Imports System.Data
Imports System.Data.SqlClient

Public Class Form1

Private ds As New DataSet()
'private cs = ConfigurationSettings.AppSettings["conMyData"]
Private cs = New SqlConnection("Data Source=.\SQLEXPRESS1;Initial Catalog=MYDATA;Integrated Security=True")
Private da = New SqlDataAdapter()
Private tblStudentBS = New BindingSource() 'สำหรับผูก dataset กับ object

' For Add, Edit Record
Private lNew As Boolean
Private cKey As String

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DisplayData()
'ผูก ds กับ object
tblStudentBS.DataSource = ds.Tables("tblStudent") 'tblStudentBS.DataSource = ds.Tables(0)
txtStudent_ID.DataBindings.Add(New Binding("Text", tblStudentBS, "Student_ID"))
txtFirstName.DataBindings.Add(New Binding("Text", tblStudentBS, "FirstName"))
txtLastName.DataBindings.Add(New Binding("Text", tblStudentBS, "LastName"))

Me.SplitContainer1.Panel2.Enabled = False

Me.btnSave.Enabled = False
Me.btnCancel.Enabled = False
End Sub

Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
DisplayData()
End Sub

Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
DisplayData()
End Sub

Private Sub btnFirst_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFirst.Click
tblStudentBS.MoveFirst()
dgUpdate()
End Sub

Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrevious.Click
tblStudentBS.MovePrevious()
dgUpdate()
End Sub

Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
tblStudentBS.MoveNext()
dgUpdate()
End Sub

Private Sub btnLast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLast.Click
tblStudentBS.MoveLast()
dgUpdate()
End Sub

Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
txtStudent_ID.Text = ""
txtFirstName.Text = ""
txtLastName.Text = ""
lNew = True
onEntry()
End Sub

Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
Try
cKey = ds.Tables("tblStudent").Rows(tblStudentBS.Position)(0) 'Column 0 is key field
lNew = False
onEntry()
Catch ex As Exception
'
End Try
End Sub

Private Sub onEntry()
SplitContainer1.Panel2.Enabled = True
txtStudent_ID.Focus()
SplitContainer1.Panel1.Enabled = False
btnNew.Enabled = False
btnEdit.Enabled = False
btnDelete.Enabled = False
btnSave.Enabled = True
btnCancel.Enabled = True
End Sub

Private Sub offEntry()
SplitContainer1.Panel1.Enabled = True
txtSearch.Focus()
SplitContainer1.Panel2.Enabled = False
btnNew.Enabled = True
btnEdit.Enabled = True
btnDelete.Enabled = True
btnSave.Enabled = False
btnCancel.Enabled = False
End Sub

Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
Try
Dim dr As DialogResult
dr = MessageBox.Show("Are Your sure?" & vbLf & "There is no undo once data is deleted", "confirm Deletion", MessageBoxButtons.YesNo)
If dr = DialogResult.Yes Then
da.DeleteCommand = New SqlCommand("DELETE FROM tblStudent WHERE Student_Id = @Student_Id", cs)
da.DeleteCommand.Parameters.Add("@Student_Id", SqlDbType.VarChar).Value = ds.Tables("tblStudent").Rows(tblStudentBS.Position)(0)
cs.Open()
da.DeleteCommand.ExecuteNonQuery()
Else
MessageBox.Show("Cancel Delete")
End If
Catch ex As Exception
'
Finally
cs.Close()
DisplayData()
End Try
End Sub

Private Sub DisplayData()
da.SelectCommand = New SqlCommand("SELECT * FROM tblStudent WHERE Student_id LIKE '%" & txtSearch.Text.Trim.ToString & "%' ORDER BY Student_Id", cs)
ds.Clear()
da.Fill(ds, "tblStudent")
dg.DataSource = tblStudentBS ' dg.DataSource = ds.Tables(0)
End Sub

Private Sub dgUpdate()
dg.ClearSelection()
dg.Rows(tblStudentBS.Position).Selected = True
End Sub

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
If lNew Then
RecordAdd()
Else
RecordEdit()
End If
offEntry()
End Sub

Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
DisplayData()
If lNew Then
' nothing
Else
' Set the Position property to the results of the Find method.
Dim itemFound As Integer = tblStudentBS.Find("Student_Id", cKey)
tblStudentBS.Position = itemFound
End If
offEntry()
End Sub

Private Sub RecordAdd()
Try
''-------- for show connection ---------
'cs.Open()
'MessageBox.Show(cs.State.ToString())
'cs.Close()
''-------- for show connection ---------

Dim findID As String = txtStudent_ID.Text
da.InsertCommand = New SqlCommand("INSERT INTO tblStudent VALUES(@Student_Id, @FirstName, @LastName)", cs)
da.InsertCommand.Parameters.Add("@Student_Id", SqlDbType.VarChar).Value = txtStudent_ID.Text
da.InsertCommand.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text
da.InsertCommand.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text
cs.Open()
da.InsertCommand.ExecuteNonQuery()

' Set the Position property to the results of the Find method.
Dim itemFound As Integer = tblStudentBS.Find("Student_Id", findID)
tblStudentBS.Position = itemFound
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
cs.Close()
DisplayData()
End Try
End Sub

Private Sub RecordEdit()
Dim x As Integer
Try
da.UpdateCommand = New SqlCommand("UPDATE tblStudent SET Student_Id = @Student_Id, FirstName = @FirstName, LastName = @LastName WHERE Student_id = @Student_id_old", cs)
da.UpdateCommand.Parameters.Add("@Student_id", SqlDbType.VarChar).Value = txtStudent_ID.Text
da.UpdateCommand.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text
da.UpdateCommand.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text
da.UpdateCommand.Parameters.Add("@Student_id_old", SqlDbType.VarChar).Value = cKey 'ds.Tables("tblStudent").Rows(tblStudentBS.Position)(0)
cs.Open()
x = da.UpdateCommand.ExecuteNonQuery()

'
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
cs.Close()
DisplayData()
'If (x >= 1) Then
' Set the Position property to the results of the Find method.
Dim itemFound As Integer = tblStudentBS.Find("Student_Id", cKey)
tblStudentBS.Position = itemFound
'End If

End Try
End Sub

End Class



Create Database in SQL Server : Database Name = MYDATA



Create Table : Table Name = tblStudent

USE [MYDATA]
GO

CREATE TABLE [dbo].[tblStudent](
[STUDENT_ID] [varchar](13) NOT NULL,
[FIRSTNAME] [varchar](50) NULL,
[LASTNAME] [varchar](50) NULL,
CONSTRAINT [PK_tblStudent] PRIMARY KEY CLUSTERED
(
[STUDENT_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

สวัสดี ขอให้สนุกกับการสร้างฟอร์มป้อนข้อมูล

1 ความคิดเห็น:

suwat กล่าวว่า...

อาจารย์ครับยาวมาครับผม

"I Believe in You"

Copyright(c) 2007 - 2022 by Kasem Kamolchaipisit.