Database Storage with the ASP.NET Web Matrix - Error message
(Page 5 of 6 )
Go back to the Web Matrix and drag another label onto the page so that it sits next to the Username textbox. Make the text red and remove the Text value once again, and this time, set the ID to lblUsernameError.
Now in order to catch the exception thrown by SQL when a pre-existing value is passed to the table, you just need to add two lines of code to the INSERT function. Near the bottom of the function is the Try structure that attempts to write to the database. Add the following statement directly below the rowsAffected = dbCommand.ExecuteNonQuery:
Catch e as Exception
lblUsernameError.Text = "* This username has already been
taken"
Save the file and run it again, attempting to add a duplicate username. Your red error message should be displayed on the page.
Once either of these messages has been displayed, they remain on the page even after a refresh. A simple way to stop this is to add the following code to the top of the btnSubmit_Click sub:
lblUsernameError.Text = ""
lblPasswordError.Text = ""
Now if the problem is corrected by the user, and the form is resubmitted successfully, the red error messages disappear. For the sake of completeness, you can also add at this point a confirmation message when the operation is a success. In the Design view of the Web Matrix, drag a final label to below the two buttons; set the fore color to green this time and the ID to lblSuccess. Remove the Text value.
Now head back to the INSERT function and find the Finally statement of the Try code block. Below the connection close call, add this method:
lblSuccess.Text = "Thank you for registering, yada, yada, yada"
Run the page again and a successful submission will result in the green message.
Next: Password security >>
More Database Articles
More By Dan Wellman