I have crated a userform in access 2007 and used this code to insert in table.
Private Sub Save_Click()
If School.Value = “” Then
MsgBox (“Enter School ID”)
School.SetFocus
Exit Sub
End If
Dim insertstring As String
DoCmd.SetWarnings (False)
insertstring = “INSERT INTO Classroom (School_id) VALUES ('” & School.Value & “’ );”
DoCmd.RunSQL insertstring
end sub
When i press SAVE command for the first time with Schooltxtbox empty, the values are inserted into table without checking if the text box for school is empty. Again for the second time when i click save then it only the checks for the textbox if its empty. Why is this psl help…
if School.Value == “”
This produce compile error while using ==
My above code works well, but it doesn’t check the text box in first press to command, it insert blank in the table in first and for next entry only it checks for the text box if it’s empty or not.
Agree with NightStalker-DNS on using String.IsNullOrEmpty, but I’d take it one step further and use String.IsNullOrWhiteSpace
Try the following:
[highlight=VB.NET]Private Sub Save_Click()
If String.IsNullOrWhiteSpace(School.Value) Then
MsgBox (“Text Box is empty”)
else
Msgbox(" Not Empty")
End If
End Sub
If that continues to fail, try the following:
[highlight=VB.NET]Private Sub Save_Click()
If School.Value.Trim().Length = 0 Then
MsgBox ("Text Box is empty")
else
Msgbox(" Not Empty")
End If
End Sub
Thanks Cpradio, it worked well and Now i have another question :
I have used the following code to delete record form table:
DoCmd.RunSQL “DELETE * FROM Tbl1 WHERE Grade = '” & txtGrade.Value & “'” This works and
what if i want the query to watch two values from the table like Grade and Year or even third value like School_Nmae and delete the one that matches all these values i put in textbox to delete.
p.s Make it also for number values, how should the code be ( Colons like things)
Actually, I’m a bit surprised that even works, as I would have thought the * between DELETE and FROM would fail, however, if it works, it works. To expand it to only delete values that match on multiple columns, your syntax would be
DoCmd.RunSQL "DELETE FROM Tbl1 WHERE Grade = '" & txtGrade.Value & "' AND Year = '" & txtYear.Value & "' AND School_Name = '" & School.value & "'"
However, I will say this, you have opened yourself to a SQL Injection with this process so be sure to sanitize your data (verify it is legit). Granted I see this is against an Access database, so your tools to do that, may be limited.