Click here to Skip to main content
16,017,502 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
hi mates I am creating E-commerce website in Asp.net c# the problem which I am facing when ever i entered the quantity in the textbox & press add to cart button its not adding the same quantity to the cart and its taking all the available quantity of the product from the database and show the price for all the quantity plz help here i share my codes

What I have tried:

ASPX
  1  <%@ Page Title="" Language="C#" MasterPageFile="~/Shopping website/user/user.Master" AutoEventWireup="true" CodeFile="product_desc.aspx.cs" Inherits="Shopping_website_user_product_desc"  EnableEventValidation="false" ValidateRequest="false" %>
  2  
  3  <asp:Content ID="Content1" ContentPlaceHolderID="c1" Runat="Server">
  4     
  5  
  6      <asp:Repeater ID="d1" runat="server">
  7          <HeaderTemplate>
  8          </HeaderTemplate>
  9          <ItemTemplate>
 10              <section class="product-section">
 11  		<div class="container">
 12              <div class="row">
 13  				<div class="col-lg-6">
 14  					<div class="product-pic-zoom">
 15          <img src='../<%#Eval("product_images") %>' height="400" width="400" alt="" />
 16           </div>
 17                      <div class="product-thumbs" tabindex="1" style="overflow: hidden; outline: none;">
 18                           </div>
 19                      <div class="col-lg-6 product-details">
 20                          <h4 class="p-stock">Available: <span>In Stock</span></h4>
 21  					<div class="p-rating">
 22  						<i class="fa fa-star-o">
 23  						<i class="fa fa-star-o"></i>
 24  						<i class="fa fa-star-o">
 25  						<i class="fa fa-star-o fa-fade">
 26  					</div>
 27                           
 28              <br /> product=<%#Eval("product_name") %><br />product desc=<%#Eval("product_desc") %><br />product price=<%#Eval("product_price") %><br />product qty=<%#Eval("product_qty") %><br /></div>
 29                              
 30                      </div> 
 31                  </div>
 32                  </div>
 33                 
 34                  </section>
 35                 
 36          </ItemTemplate>
 37          <FooterTemplate>
 38          </FooterTemplate>
 39      </asp:Repeater>
 40         
 41      <br />
 42      <br />
 43          <br />
 44      <br />
 45          <br />
 46      <br />
 47      <br />
 48      <br />
 49      <table>
 50          <tr>
 51             <td><asp:Label ID="l2" runat="server" Text="Enter Quantity" BackColor="White" BorderColor="Red" Font-Bold="True" Font-Size="Large" ForeColor="Black"></asp:Label></td> 
 52              <td><asp:TextBox ID="t1" runat="server" Height="35px" Font-Bold="True" Font-Size="Larger"></asp:TextBox></td>
 53              <td><asp:Button ID="b1" runat="server" Text="Add to cart" OnClick="b1_Click" BackColor="#FFCCCC" BorderColor="#FF0066" Height="35px" Width="99px" Font-Bold="True" Font-Size="Large" />^__i class="fa" style="font-size:24px"></td>
 54  
 55          </tr>
 56          <tr>
 57              <td colspan="3">
 58                   <asp:Label ID="lblPrice" runat="server"></asp:Label>
 59                  <asp:Label ID="l1" runat="server" ForeColor="Red" Text=""></asp:Label>
 60              </td>
 61          </tr>
 62      </table> 
 63      <div id="accordion" class="accordion-area">
 64  						<div class="panel">
 65  							<div class="panel-header" id="headingOne">
 66  								<button class="panel-link active" data-toggle="collapse" data-target="#collapse1" aria-expanded="true" aria-controls="collapse1">information</button>
 67  							</div>
 68  							<div id="collapse1" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
 69  								<div class="panel-body">
 70  									<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pharetra tempor so dales. Phasellus sagittis auctor gravida. Integer bibendum sodales arcu id te mpus. Ut consectetur lacus leo, non scelerisque nulla euismod nec.</p>
 71  									<p>Approx length 66cm/26" (Based on a UK size 8 sample)</p>
 72  									<p>Mixed fibres</p>
 73  									<p>The Model wears a UK size 8/ EU size 36/ US size 4 and her height is 5'8"</p>
 74  								</div>
 75  							</div>
 76  						</div>
 77  						<div class="panel">
 78  							<div class="panel-header" id="headingTwo">
 79  								<button class="panel-link" data-toggle="collapse" data-target="#collapse2" aria-expanded="false" aria-controls="collapse2">care details </button>
 80  							</div>
 81  							<div id="collapse2" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion">
 82  								<div class="panel-body">
 83  									<img src="./img/cards.png" alt="">
 84  									<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pharetra tempor so dales. Phasellus sagittis auctor gravida. Integer bibendum sodales arcu id te mpus. Ut consectetur lacus leo, non scelerisque nulla euismod nec.</p>
 85  								</div>
 86  							</div>
 87  						</div>
 88  						<div class="panel">
 89  							<div class="panel-header" id="headingThree">
 90  								<button class="panel-link" data-toggle="collapse" data-target="#collapse3" aria-expanded="false" aria-controls="collapse3">shipping & Returns</button>
 91  							</div>
 92  							<div id="collapse3" class="collapse" aria-labelledby="headingThree" data-parent="#accordion">
 93  								<div class="panel-body">
 94  									<h4>7 Days Returns</h4>
 95  									<p>Cash on Delivery Available<br>Home Delivery <span>3 - 4 days</span></p>
 96  									<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pharetra tempor so dales. Phasellus sagittis auctor gravida. Integer bibendum sodales arcu id te mpus. Ut consectetur lacus leo, non scelerisque nulla euismod nec.</p>
 97  								</div>
 98  							</div>
 99  						</div>
100  					</div>
101         
102  </asp:Content>
C#
  1  using System.Linq;
  2  using System.Web;
  3  using System.Web.UI;
  4  using System.Web.UI.WebControls;
  5  using System.Data;
  6  using System.Data.SqlClient;
  7  using System.Configuration;
  8  
  9  public partial class Shopping_website_user_product_desc : System.Web.UI.Page
 10  {
 11      SqlConnection con = new SqlConnection(@"Data Source=_SONY_\SQLEXPRESS;Initial Catalog=shoppingmaster;Integrated Security=True;Pooling=False");
 12      int id;
 13      int qty;
 14      string product_name, product_desc, product_price, product_qty, product_images;
 15      protected void Page_Load(object sender, EventArgs e)
 16      {
 17          if (Request.QueryString["id"] == null)
 18          {
 19              Response.Redirect("display_item.aspx");
 20          }
 21          else
 22          {
 23  
 24              id = Convert.ToInt32(Request.QueryString["id"].ToString());
 25              con.Open();
 26              SqlCommand cmd = con.CreateCommand();
 27              cmd.CommandType = CommandType.Text;
 28              cmd.CommandText = "select * from product where id=" + id + "";
 29              cmd.Parameters.AddWithValue("@id", id);
 30              cmd.ExecuteNonQuery();
 31              DataTable dt = new DataTable();
 32              SqlDataAdapter da = new SqlDataAdapter(cmd);
 33              da.Fill(dt);
 34              d1.DataSource = dt;
 35              d1.DataBind();
 36  
 37              con.Close();
 38  
 39          }
 40          
 41          qty = get_qty(id);
 42  
 43          if (qty == 0)
 44          {
 45              l2.Visible = false;
 46              t1.Visible = false;
 47              b1.Visible = false;
 48              l1.Text = "Their is no  availabe quantity of this item";
 49  
 50          }
 51      }
 52  
 53  
 54  
 55  
 56      protected void b1_Click(object sender, EventArgs e)
 57      {
 58          if (con.State == ConnectionState.Open)
 59          {
 60              con.Close();
 61  
 62          }
 63          {
 64              int product_qty = Convert.ToInt32(t1.Text); // get the quantity of products ordered from the text box
 65  
 66              double product_price = 0;
 67  
 68              // get the product from the database
 69              using (var connection = new SqlConnection(@"Data Source=_SONY_\SQLEXPRESS;Initial Catalog=shoppingmaster;Integrated Security=True;MultipleActiveResultSets=true;Pooling=False"))
 70              {
 71                  connection.Open();
 72                  using (var command = new SqlCommand("SELECT * FROM Product WHERE Id = @Id", connection))
 73                  {
 74                      command.Parameters.AddWithValue("@Id", id); // use the selected product ID to retrieve the product from the database
 75                      using (var reader = command.ExecuteReader())
 76                      {
 77                          if (reader.Read())
 78                          {
 79                              // get the price from the database
 80                              product_price = Convert.ToDouble(reader["product_price"]);
 81                          }
 82                      }
 83                  }
 84              }
 85  
 86              // calculate the total price for the quantity ordered
 87              double totalPrice = product_price * product_qty;
 88  
 89              // display the total price to the customer
 90              lblPrice.Text = "Total Price: " + totalPrice.ToString("C2");
 91          }
 92  
 93          con.Close();
 94  
 95          // this is for getting user details and stroing it on order_details table
 96          con.Open();
 97          SqlCommand cmd = con.CreateCommand();
 98          cmd.CommandType = CommandType.Text;
 99          cmd.CommandText = "select * from registration where email='" + Session["user"].ToString() + "'";
100          cmd.ExecuteNonQuery();
101          DataTable dt1 = new DataTable();
102          SqlDataAdapter da1 = new SqlDataAdapter(cmd);
103          da1.Fill(dt1);
104          foreach (DataRow dr in dt1.Rows)
105          {
106              SqlCommand cmd3 = con.CreateCommand();
107              cmd3.CommandType = CommandType.Text;
108              cmd3.CommandText = "insert into orders values('" + dr["firstname"].ToString() + "','" + dr["lastname"].ToString() + "','" + dr["email"].ToString() + "','" + dr["address"].ToString() + "','" + dr["city"].ToString() + "','" + dr["state"].ToString() + "','" + dr["pincode"].ToString() + "','" + dr["mobile"].ToString() + "','" + dr["date"].ToString() + "','" + dr["DateofOrder"].ToString() + "')";
109              cmd3.ExecuteNonQuery();
110  
111          }
112  
113          SqlCommand cmd10 = con.CreateCommand();
114          cmd10.CommandType = CommandType.Text;
115          cmd10.CommandText = "select * from orders where id=" + id + "";
116          cmd10.ExecuteNonQuery();
117          DataTable dt3 = new DataTable();
118          SqlDataAdapter da3 = new SqlDataAdapter(cmd10);
119          da3.Fill(dt3);
120         
121         
122          SqlCommand cmd4 = con.CreateCommand();
123          cmd4.CommandType = CommandType.Text;
124          cmd4.CommandText = "select * from product where id=" + id + "";
125          cmd4.ExecuteNonQuery();
126          DataTable dt = new DataTable();
127          SqlDataAdapter da = new SqlDataAdapter(cmd4);
128          da.Fill(dt);
129          foreach (DataRow dr in dt.Rows)
130          {
131              product_name = dr["product_name"].ToString();
132              product_desc = dr["product_desc"].ToString();
133              product_price = dr["product_price"].ToString();
134              product_qty = dr["product_qty"].ToString();
135              product_images = dr["product_images"].ToString();
136  
137          }
138  
139  
140          if (Convert.ToInt32(t1.Text) > Convert.ToInt32(product_qty))
141          {
142              l1.Text = "Please Enter lower Quantity";
143          }
144          else
145          {
146              l1.Text = "";
147  
148          }
149  
150  
151          if (Request.Cookies["aa"] == null)
152          {
153              Response.Cookies["aa"].Value = product_name.ToString() + "," + product_desc.ToString() + "," + product_price.ToString() + "," + product_qty.ToString() + "," + product_images.ToString() + "," + id.ToString();
154              Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);
155  
156          }
157          else
158          {
159              Response.Cookies["aa"].Value = Request.Cookies["aa"].Value + "|" + product_name.ToString() + "," + product_desc.ToString() + "," + product_price.ToString() + "," + product_qty.ToString() + "," + product_images.ToString() + "," + id.ToString();
160              Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);
161          }
162  
163          SqlCommand cmd1 = con.CreateCommand();
164          cmd1.CommandType = CommandType.Text;
165          cmd1.CommandText = "update product set product_qty=product_qty-" + t1.Text + "where id=" + id;
166          cmd1.ExecuteNonQuery();
167          Response.Redirect("product_desc.aspx?id=" + id.ToString());
168  
169  
170  
171          {
172              string id = Request.QueryString["id"];
173              if (Session["user"] == null)
174              {
175                  Response.Redirect("login.aspx");
176              }
177              else
178              {
179                  try
180                  {
181                      SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["shoppingmaster"].ConnectionString);
182                      con.Open();
183  
184                      // Retrieve product quantity and price from the 'product' table
185                      SqlCommand cmd15 = con.CreateCommand();
186                      cmd15.CommandType = CommandType.Text;
187                      cmd15.CommandText = "SELECT product_qty, product_price FROM product WHERE Id=@id";
188                      cmd15.Parameters.AddWithValue("@id", id);
189                      SqlDataReader dr = cmd15.ExecuteReader();
190                      if (dr.Read())
191                      {
192                          int product_qty = Convert.ToInt32(dr["product_qty"]);
193                          int product_price = Convert.ToInt32(dr["product_price"]);
194                          int quantity = Convert.ToInt32(t1.Text);
195                          if (quantity > product_qty)
196                          {
197                              Response.Write("<script>alert('We do not have sufficient quantity in stock!')</script>");
198                          }
199                          else
200                          {
201                              // Insert the item into the 'cart' table
202                              SqlCommand cmd2 = con.CreateCommand();
203                              cmd2.CommandType = CommandType.Text;
204                              cmd2.CommandText = "INSERT INTO cart (quantity, price, product_id, user_id) VALUES (@quantity, @price, @product_id, @user_id)";
205                              cmd2.Parameters.AddWithValue("@quantity", quantity);
206                              cmd2.Parameters.AddWithValue("@price", product_price);
207                              cmd2.Parameters.AddWithValue("@product_id", id);
208                              cmd2.Parameters.AddWithValue("@user_id", Session["user"].ToString());
209                              int rowsAffected = cmd2.ExecuteNonQuery();
210  
211                              // Check if the insert was successful
212                              if (rowsAffected > 0)
213                              {
214                                  Response.Redirect("product_desc.aspx?id=" + id.ToString());
215                              }
216                              else
217                              {
218                                  Response.Write("<script>alert('Failed to add item to cart!')</script>");
219                              }
220                          }
221                      }
222                      con.Close();
223                  }
224                  catch (Exception ex)
225                  {
226                      Response.Write("<script>alert('Error: " + ex.Message + "')</script>");
227                  }
228              }
229          }
230      }
231  
232  
233  
234  public int get_qty(int id)
235  {
236      con.Open();
237      SqlCommand cmd = con.CreateCommand();
238      cmd.CommandType = CommandType.Text;
239      cmd.CommandText = "select * from product where id=" + id + "";
240      cmd.ExecuteNonQuery();
241      DataTable dt = new DataTable();
242      SqlDataAdapter da = new SqlDataAdapter(cmd);
243      da.Fill(dt);
244      foreach (DataRow dr in dt.Rows)
245      {
246          qty = Convert.ToInt32(dr["product_qty"].ToString());
247      }
248      return qty;
249  
250          
251  }
252  }
Posted
Updated 27-Feb-23 22:23pm
v2
Comments
Graeme_Grant 27-Feb-23 22:05pm    
That is quite the code dump. You're doing a postback. Have you set a breakpoint and viewed the postback data? What do you see?
Member 12187964 28-Feb-23 1:38am    
I JUST CANT SOLVE IT :(

You have a bigger problem than that ... never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
 
Share this answer
 
Comments
Andre Oosthuizen 28-Feb-23 4:37am    
Concise and clear = +5
Griff is right - you urgently need to fix the SQL Injection[^] vulnerabilities in your code.

You also need to understand the basics of ADO.NET:
Overview - ADO.NET | Microsoft Learn[^]

For example, you're adding a parameter to your command, but the command doesn't use it. You're calling ExecuteNonQuery on a SELECT command. You're then using a SqlDataAdapter to execute the command again.

You should also wrap any disposable objects in a using block, to ensure they're always disposed of properly.

You shouldn't store SqlConnection objects in class-level fields. Instead, create them when they're needed, and dispose of them as soon as you're done with them.

And you should avoid hard-coding your connection string in your pages; instead, store it in the web.config file:
Store Connection String in Web.config - ConnectionStrings.com[^]

Eg:
C#
public partial class Shopping_website_user_product_desc : System.Web.UI.Page
{
    private static SqlConnection CreateConnection()
    {
        return new SqlConnection(@"Data Source=_SONY_\SQLEXPRESS;Initial Catalog=shoppingmaster;Integrated Security=True;Pooling=False");
        
        // Or preferably:
        // return new SqlConnection(WebConfigurationManager.ConnectionStrings["ShoppingMaster"].ConnectionString);
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack) return; // Don't re-bind the page on postback
        
        int id;
        if (!int.TryParse(Request.QueryString["id"], out id))
        {
            Response.Redirect("display_item.aspx");
            return;
        }
        
        BindList(id);
    }
    
    private void BindList(int id)
    {
        using (SqlConnection con = CreateConnection())
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM product WHERE id = @id", con))
        {
            cmd.Parameters.AddWithValue("@id", id);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            
            d1.DataSource = dt;
            d1.DataBind();
        }
    }
    
    ...
 
Share this answer
 
Comments
Andre Oosthuizen 28-Feb-23 4:36am    
Concise and clear = +5
Member 12187964 28-Feb-23 15:39pm    
mate can u help me ... anydesk ....
Richard Deeming 1-Mar-23 3:44am    
No. Any help happens on the site; nobody is going to offer to connect to your computer and be your personal assistant.

And if anyone does offer to connect to your computer, then you should be very suspicious: they're probably a scammer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900