ถ้าใน DB ไม่มีข้อมูลถึงจะ error ครับ ถ้าใส่ข้อมูล "RM0001" ไปก่อนถึงจะทำงานได้ครับ
Code (VB.NET)
Dim intNum As String = Nothing
Dim Count As Integer
ConnectDB()
strSQL = "SELECT MAX(RIGHT(RM_ID,4)) AS RM_ID FROM RawMaterial_New"
objCmd = New SqlCommand(strSQL, objConn)
objConn.Open()
Count = objCmd.ExecuteScalar()
objConn.Close()
Dim iMAX As Integer = IIf(Count <= 0, 1, Count + 1)
If iMAX < 10000 Then
strSQL = "INSERT INTO RawMaterial_New (RM_ID) VALUES ('" & iMAX.ToString("RM0000") & "')"
objCmd = New SqlCommand(strSQL, objConn)
objConn.Open()
objCmd.ExecuteNonQuery()
objConn.Close()
MsgBox("บันทึกสำเร็จ")
Else
MsgBox("ข้อมูลเต็ม")
End If
Tag : .NET, Ms SQL Server 2008, Web (ASP.NET), VB.NET, VS 2012 (.NET 4.x)
Imports System.Data.SqlClient
Public Class Manage_RawMaterial_New
Inherits System.Web.UI.Page
Dim objConn As SqlConnection
Dim objCmd As SqlCommand
Dim strConnString, strSQL As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Sub ConnectDB()
strConnString = ConfigurationManager.ConnectionStrings("con").ConnectionString
objConn = New SqlConnection(strConnString)
End Sub
Private Sub AddAutoID()
Try
Dim intNum As String = Nothing
Dim Count As Integer
ConnectDB()
strSQL = "SELECT ISNULL(MAX(RIGHT(RM_ID,4)),0) AS RM_ID FROM RawMaterial_New"
objCmd = New SqlCommand(strSQL, objConn)
objConn.Open()
Count = objCmd.ExecuteScalar()
objConn.Close()
Dim iMAX As Integer = IIf(Count <= 0, 1, Count + 1)
If iMAX < 10000 Then
strSQL = "INSERT INTO RawMaterial_New (RM_ID) VALUES ('" & iMAX.ToString("RM0000") & "')"
objCmd = New SqlCommand(strSQL, objConn)
objConn.Open()
objCmd.ExecuteNonQuery()
objConn.Close()
MsgBox("บันทึกสำเร็จ")
Else
MsgBox("ข้อมูลเต็ม")
End If
Catch ex As Exception
Response.Write("Error : " + ex.Message)
End Try
End Sub
Protected Sub btnRM_Add_Click(sender As Object, e As EventArgs) Handles btnRM_Add.Click
AddAutoID()
End Sub
End Class