This sample shows how to check user input against data already in a database. In many cases, when a user is ‘signing up’ for a web site, he/she is asked to choose a username and password. Here, you will see how to use the SQL Managed Provider to query the database BEFORE inserting the user id into the database.
To see a code sample of how to insert data from a form, into a database, check out this sample:
Inserting Record into Database.
Here, we just use the Employees Table of the Northwind Database, but we add a UID (and password, if you want to complete the functionality) column/field to the table.
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.2">
<title>Checking User ID in Database</title>
<script language="VB" runat="server">
Dim intCount as Integer
Sub doCheck(Source as Object, E as EventArgs)
Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDB"
Dim MySQL as string = "Select Count(uid) from Employees where uid=@uid"
Dim MyConn as New SQLConnection(strConn)
Dim Cmd as New SQLCommand(MySQL, MyConn)
cmd.Parameters.Add(New SQLParameter("@uid", txtuid.text))
MyConn.Open()
intCount=Cmd.ExecuteScalar
MyConn.Close
if intCount>0 then
label1.text="Sorry, that user id is already taken. Try another"
else
label1.text ="The user id you chose is not being used "
''here, you would insert the user information into the database
End If
End Sub
</script>
</head>
<body>
<Form id="form1" runat="server">
Enter User Name and Password you would like to use:<br>
<table> <tr>
<td align="Right" valign="Top">User ID: </td>
<td align="Left" valign="Top"><asp:TextBox id="txtUID" runat="server" /></td></tr>
<tr>
<td align="Right" valign="Top">PWD: </td>
<td align="Left" valign="Top"><asp:TextBox id="txtPWD" runat="server" /></td>
</tr>
<tr>
<td align="right" valign="Top" Colspan="2"><asp:Button id="button1" Text="Submit" onclick="doCheck" runat="server" /></td>
</tr>
</table>
<asp:Label ID="label1" runat="server" />
</Form>
</body>
</html>