The following code inserts a record into the Microsoft Access database when the form fields are completed and the button 'Button1' clicked. The Access database is called 'Customers' and has a table called 'tblCustomers'. The table has a primary key autonumber field 'ID', and two textfields 'FirstName' and 'LastName'. The database is located in the folder 'H:\Inetpub\wwwroot\code\Customers.mdb'.
A label control 'label1' displays the text 'Please insert a record' when the page is first loaded. When the button is clicked the click event of the button is raised and a postback occurs with the Button1_Click method being executed. The Button1_Click method inserts the form details into the database.
The sample below is very straightforward and for simplicity leaves out any form validation or error trapping. To ensure an error doesn't happen if either textbox is left blank you should atleast include form validation. (ASP.NET form to database tutorial with validation)
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data.Oledb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub Page_Load()
Label1.Text = "Please insert a record."
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim Connection As New OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" & _
"Data Source=H:\Inetpub\wwwroot\code\Customers.mdb")
Connection.Open()
Dim Command As New OleDbCommand("INSERT INTO tblCustomers(FirstName," & _
"LastName)VALUES(@FirstName,@LastName)", Connection)
Command.Parameters.Add(New OleDbParameter("@FirstName", TextBox1.Text))
Command.Parameters.Add(New OleDbParameter("@LastName", TextBox2.Text))
Command.ExecuteNonQuery()
Connection.Close()
Label1.Text = "Record inserted."
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id=Head1 runat="server">
<title>ASP.NET Form to Database Sample</title>
</head>
<body>
<div>
<form id="form1" runat="server">
First name:<asp:TextBox ID=TextBox1 runat="server"></asp:TextBox><br />
Last name:<asp:TextBox ID=TextBox2 runat="server"></asp:TextBox><br />
<asp:Button ID=Button1 runat="server" Text="Insert Record" OnClick=Button1_Click />
<br />
<asp:Label ID=Label1 runat="server" Text="Label"></asp:Label>
</form>
</div>
</body>
</html>
Get the best asp web hosting provider now and save 30%
Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.