Многие объяснения уже присутствуют, чтобы объяснить, как это происходит и как это исправить, но вы также должны следовать рекомендациям, чтобы избежать NullPointerException
вообще.
См. также: A хороший список лучших практик
Я бы добавил, очень важно, хорошо использовать модификатор final
. Использование "окончательной" модификатор, когда это применимо в Java
Сводка:
final
для обеспечения хорошей инициализации. @NotNull
и @Nullable
if("knownObject".equals(unknownObject)
valueOf()
поверх toString (). StringUtils
StringUtils.isEmpty(null)
. Я думаю, что функция доступа LAST решит вашу проблему.
Private Function GetLastID() As String
Dim LastID As String = ""
Try
'The Using blocks ensure that your database objects are closed and disposed even if there is an error
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\inventory1.accdb")
'Pass the query and connection directly in to the constructor of the command
'The Access LAST function returns the field specified for the last record.
Using cmd As New OleDbCommand("SELECT Last(category_id) FROM tblcategory;", cn)
'Open the connection at the last minute.
cn.Open()
'Since you only need a single value you can use .ExecuteScalar
LastID = cmd.ExecuteScalar().ToString
End Using 'close and dispose the command
End Using 'close and dispose the connection
Catch Ex As Exception
MessageBox.Show(Ex.Message)
End Try
Return LastID
End Function
Private Function GetNewID(LastID As String) As String
Dim NewID As String
'The substring starts at a specified character position And continues to the end of the string.
NewID = "CAT00" & Convert.ToInt32(LastID.Substring(5)) + 1
Return NewID
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Assumes there is at least one record in the table
Dim LastID As String = GetLastID()
Dim NewID As String = GetNewID(LastID)
End Sub