3.If กำหนดความสั่นความยาวของ Text ที่กรอกไป เช่น 6-20 ตัว
4.If ให้กรอกได้แค่ ภาษาอังกิดกับตัวเลขเท่านั้น
ขอบคุณครับ
นี้โค๊ตที่ผมเขียนขึ่นมา
Code (VB.NET)
Imports MySql.Data.MySqlClient
Public Class Form1
Dim ServerString As String = "Server=127.0.0.1;User Id=root;Password=test;Database=test"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
MsgBox("ติดต่อฐานข้อมูลสำเร็จ !", MsgBoxStyle.Information)
Else
SQLConnection.Close()
MsgBox("ติดต่อฐานข้อมูลไม่ได้ !", MsgBoxStyle.Critical)
Me.Close()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveNames(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
MsgBox("สมัครสมาชิกสำเร็จ !", MsgBoxStyle.Information)
Me.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SQLStatement As String = "INSERT INTO user2 (username, password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
SaveNames(SQLStatement)
End Sub
End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd As MySqlCommand = New MySqlCommand
Dim SQLStatement As String = "INSERT INTO user2 (username, password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
SaveNames(SQLStatement)
End Sub
อะครับขาดแค่ If 2-4 อย่างเองพี่วินช่วยผมเติมหน่อยได้ไหมครับผม งง อะครับ
ลองแก้ไข function Savename ให้ return boolean Code (VB.NET)
'อันนี้ผมลองเป็น SqlClient นะครับ
Public Function SaveNames(ByRef SQLStatement As String) As Boolean
Dim cmd As New SqlCommand
Dim tr As SqlTransaction
tr = SqlConnection.BeginTransaction()
Try
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SqlConnection
.Transaction = tr
.ExecuteNonQuery()
End With
tr.Commit()
Return True
Catch ex As Exception
tr.Rollback()
SqlConnection.Close()
Return False
End Try
End Function
' เรียกใช้ function SaveNames
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd As MySqlCommand = New MySqlCommand
Dim SQLStatement As String = "INSERT INTO user2 (username, password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
'เรียกใช้ function SaveNames
If SaveNames(SQLStatement) = True Then
MsgBox("สมัครสมาชิกสำเร็จ !", MsgBoxStyle.Information, "บันทึกข้อมูล")
Else
MsgBox("สมัครสมาชิกไม่สำเร็จ !", MsgBoxStyle.Critical, "บันทึกข้อมูล")
End If
End Sub