Database Storage with the ASP.NET Web Matrix - Coding the page
(Page 4 of 6 )
This is all the page needs visually, the rest will be code run behind the scenes. Switch to the Code view using the tabs at the bottom of the document window. The Code Wizards toolbox will appear. From here, drag the INSERT Data Method onto the page to open the INSERT Data Code Wizard dialog box. Your database, unless you have more than one configured connection, will appear in the Select a Database box, so click the next button. Make sure your logins table is selected in the next window and simply click Next again (neither of the columns in the right-hand panel need to be ticked). Now just choose a name for your method, like NewUser, and click Finish.
Your code page should now contain the block of code needed to write data to your table. Before this can happen however, you need to define a way of calling the function and telling it what data to write. Go back to the Design view of the document page and double click the submit button, which will create a new onclick event handler for the button, and add some more code to the Code view.
Switch back to the Code view and in between the new code that has been added type:
If txtPassword.Text <> txtPassword2.Text Then
lblPasswordError.Text = "* Verify password must match
password"
Else
NewUser(txtUsername.Text, txtPassword.Text)
End if
This is all that is needed to check that the two password fields match and if so, call the function and pass it the contents of each text box as a parameter. When the password fields do not match, the text property of the label following the verify password box is set to the error message. This needs to be done because, unfortunately, the MessageBox.Show VB.NET method does not work with ASP.NET.
To create functionality for the clear button, switch back to the Design view and double click the clear button. In between the lines of new code added to the Code view, add:
txtUsername.Text = ""
txtPassword.Text = ""
txtPassword2.Text = ""
To test the page so far, click the play button at the top of the Web Matrix. Assuming all is well, if you enter a username and password into the text boxes and click the submit button, the text entered will be written to your database table. To verify this, go back to the Web Matrix and double click the table in the Data Pane.
Once thing you should remind yourself of at this point is that we set the IsUniqueKey of the username column of our data table to true, therefore, if you try to enter the same username on the form twice, you’ll get a nasty looking error page. Users should not be subject to this kind of abuse, so you’re going to want something that will present a proper error message to the user. You can use the same display method for the error as the verify password message above.
Next: Error message >>
More Database Articles
More By Dan Wellman