SQL Server Database Crud operation in ASP.NET (VB)

Total Post:70

 4049  View(s)
Rate this:

I am currently learning to write ASP.NET website using Visual Studio Express 2013 for Web, and I plan to develop an online shopping website. I have started a New Web Site, added a SQL Server Database (eCommerce.mdf) into the WebSite (in VS), created two tables and inserted a row of data using the following query:

CREATE TABLE product (product_id char(4) PRIMARY KEY, product_name varchar(50), product_price money, product_stock int);
INSERT INTO product VALUES ('P001', 'Omega Seamaster Planet Ocean 600m', 68000, 7);
CREATE TABLE cart (customer_id char(4), product_id char(4), cart_quantity int);



Then I have added a new web form Product.aspx into the website and a GridView to get data from the product table (it shows SelectCommand="SELECT * FROM [product]" in the source) from my database. It works fine but I want to make a Button, namely Add to cart, that can do the INSERT INTO function to add new rows to the cart table. I try to use the following codes: 

Add an OnClick event in the Button html code

 <asp:Button ID="Button1" runat="server" Text="Add to cart" OnClick="func1" />


Add the script of func1 event before <html xmlns="http://www.w3.org/1999/xhtml">


<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
Sub func1()
    Dim cn As New SqlConnection("I dont know what I should type here!")
    Dim cmd = New SqlCommand("INSERT INTO cart VALUES ('C001', 'P001', 1);")
End Sub


I am not sure about the ConnectionString parameter to be passed to SqlConnection() because I have tried a lot of examples from the Internet but none of them works for me.

From connectionStrings under the Webconfig file, other than the ConnectionString with name of DefaultConnection, it writes connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\eCommerce.mdf;Integrated Security=True".

Moreover, I get the message An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code when I click the Button in debugging mode if I use OnClick event instead of OnClientClick event.

So my question is, what should I type as the ConnectionString parameter and anything else should I modify to get func1 work as expected? I also appreciate any other methods.

  1. Post:51

    Re: SQL Server Database Crud operation in ASP.NET (VB)

    You can try like this.

    Dim connectionString As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
    Dim cn As New SqlConnection(connectionString)
    Dim cmd = New SqlCommand("INSERT INTO cart VALUES ('C001', 'P001', 1);", cn)

      Modified On Apr-06-2018 02:29:33 AM