Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Mates i have an issue in product_desc page.cs when i am adding this code if (!IsPostBack) plus and minus button works fine increase and decrease but the values r not inserting into database such as product_name product_images and product_desc rest of the values r inserting properly, but when i remove this code again if (!IsPostBack) all the values insert properly in the database perfectly but plus and minus button doest work.....help

<%@ 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" %>

<asp:Content ID="Content1" ContentPlaceHolderID="c1" Runat="Server">
  <style>
       /* Main container */
       .container {
           max-width: 1200px;
           margin: 0 auto;
       }

       /* Product section */
       .product-section {
           padding: 50px 0;
       }

       /* Product image */
       .product-pic-zoom img {
           max-width: 100%;
           height: auto;
           display: block;
       }

       /* Product details */
       .product-details {
           padding: 20px;
           background-color: #f9f9f9;
       }

       .p-stock span {
           color: green;
       }

       .p-rating i {
           color: gold;
       }

       /* Quantity input */
       .quantity-input {
           display: flex;
           align-items: center;
       }

       .quantity-input input[type="text"] {
           width: 80px;
           padding: 5px;
           text-align: center;
           border: 1px solid #ccc;
           border-radius: 5px;
       }

       /* Add to cart button */
       .add-to-cart-btn {
           display: inline-block;
           padding: 10px 20px;
           background-color: #ffcccc;
           border: 1px solid #ff0066;
           color: black;
           font-weight: bold;
           font-size: 16px;
           text-decoration: none;
       }

       /* Accordion panel */
       .panel {
           margin-bottom: 20px;
       }

       .panel-header button {
           width: 100%;
           text-align: left;
           background-color: #f9f9f9;
           padding: 10px;
           border: none;
           border-bottom: 1px solid #ccc;
           color: #333;
           font-weight: bold;
           cursor: pointer;
       }

       .panel-body {
           padding: 20px;
           background-color: #f9f9f9;
           border: 1px solid #ccc;
       }
      .quantity-btn {
  font-size: 30px;
  width: 40px;
  height: 40px;
  border: 1px solid #ccc;
  background-color: #f9f9f9;
  color: #333;
}

.minus-btn {
  margin-right: 10px;
}

.plus-btn {
  margin-left: 10px;
}
    </style>

    <asp:Repeater ID="d1" runat="server">
        <HeaderTemplate>
        </HeaderTemplate>
        <ItemTemplate>
            <section class="product-section">
                <div class="container">
                    <div class="row">
                        <div class="col-lg-6">
                            <div class="product-pic-zoom">
                                <img src='../<%#Eval("product_images") %>' height="400" width="400" alt="" />
                            </div>
                            <div class="product-thumbs" tabindex="1" style="overflow: hidden; outline: none;">
                                <!-- Thumbnails -->
                            </div>
                        </div>
                        <div class="col-lg-6 product-details">
                            <h4 class="p-stock">Available: <span>In Stock</span></h4>
                            <div class="p-rating">
                                
                                ^__i class="fa fa-star-o">
                                ^__i class="fa fa-star-o fa-fade">
                            </div>
                            <p>Product: <%#Eval("product_name") %></p>
                            <p>Product Description: <%#Eval("product_desc") %></p>
                            <p>Product Price: <%#Eval("product_price") %></p>
                            <p>Product Quantity: <%#Eval("product_qty") %></p>

                            <table>
                                <tr>
                                    <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>
                                    <td>
                                        <div class="quantity-input">
    <asp:Button ID="btnMinus" runat="server" Text="-" OnClick="btnMinus_Click" CssClass="quantity-btn minus-btn" />
   <asp:TextBox ID="t1" runat="server" Height="50px" Font-Bold="True" Font-Size="Larger" Text="1" ReadOnly="false" TextMode="SingleLine" Enabled="false"></asp:TextBox>

    <asp:Button ID="btnPlus" runat="server" Text="+" OnClick="btnPlus_Click" CssClass="quantity-btn plus-btn" />
</div>
                                    </td>
                                   
                                    <td>
                                        <asp:Button ID="btnAddToCart" runat="server" Text="Add to Cart" OnClick="b1_Click" CssClass="add-to-cart-btn" />

                                        ^__i class="fa" style="font-size:24px">
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="3">
                                       <asp:Label ID="lblPrice" runat="server" Text=""></asp:Label>

                                        <asp:Label ID="l1" runat="server" ForeColor="Red" Text=""></asp:Label>

                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </section>
        </ItemTemplate>
        <FooterTemplate>
        </FooterTemplate>
    </asp:Repeater>

    <br />
    <br />

    <div class="container">
        <div class="row">
            <div class="col-lg-6">
                <div id="accordion" class="accordion-area">
                    <div class="panel">
                        <div class="panel-header" id="headingOne">
                            <button class="panel-link active" data-toggle="collapse" data-target="#collapse1" aria-expanded="true" aria-controls="collapse1">Information</button>
                        </div>
                        <div id="collapse1" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
                            <div class="panel-body">
                                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pharetra tempor sodales. Phasellus sagittis auctor gravida. Integer bibendum sodales arcu id tempus. Ut consectetur lacus leo, non scelerisque nulla euismod nec.</p>
                                <p>Approx length 66cm/26" (Based on a UK size 8 sample)</p>
                                <p>Mixed fibres</p>
                                <p>The Model wears a UK size 8/ EU size 36/ US size 4 and her height is 5'8"</p>
                            </div>
                        </div>
                    </div>
                    <div class="panel">
                        <div class="panel-header" id="headingTwo">
                            <button class="panel-link" data-toggle="collapse" data-target="#collapse2" aria-expanded="false" aria-controls="collapse2">Care Details</button>
                        </div>
                        <div id="collapse2" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion">
                            <div class="panel-body">
                                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pharetra tempor sodales. Phasellus sagittis auctor gravida. Integer bibendum sodales arcu id tempus. Ut consectetur lacus leo, non scelerisque nulla euismod nec.</p>
                                <p>Approx length 66cm/26" (Based on a UK size 8 sample)</p>
                                <p>Mixed fibres</p>
                                <p>The Model wears a UK size 8/ EU size 36/ US size 4 and her height is 5'8"</p>
                            </div>
                        </div>
                    </div>
                    <div class="panel">
                        <div class="panel-header" id="headingThree">
                            <button class="panel-link" data-toggle="collapse" data-target="#collapse3" aria-expanded="false" aria-controls="collapse3">Delivery & Returns</button>
                        </div>
                        <div id="collapse3" class="collapse" aria-labelledby="headingThree" data-parent="#accordion">
                            <div class="panel-body">
                                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pharetra tempor sodales. Phasellus sagittis auctor gravida. Integer bibendum sodales arcu id tempus. Ut consectetur lacus leo, non scelerisque nulla euismod nec.</p>
                                <p>Approx length 66cm/26" (Based on a UK size 8 sample)</p>
                                <p>Mixed fibres</p>
                                <p>The Model wears a UK size 8/ EU size 36/ US size 4 and her height is 5'8"</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6">
                <!-- Similar products -->
            </div>
        </div>
    </div>
    <script>
function increaseQuantity() {
    var quantity = parseInt(document.getElementById("t1").value);
    if (quantity > 0) {
        quantity++;
        document.getElementById("t1").value = quantity;
    }
}

function decreaseQuantity() {
    var quantity = parseInt(document.getElementById("t1").value);
    if (quantity > 1) {
        quantity--;
        document.getElementById("t1").value = quantity;
    }
}

document.getElementById("btnPlus").onclick = increaseQuantity;
document.getElementById("btnMinus").onclick = decreaseQuantity;

// Validation rule for t1 text box
var t1 = document.getElementById("t1");
t1.onkeypress = function(event) {
    var keyCode = event.keyCode;
    if (keyCode < 48 || keyCode > 57) {
        event.preventDefault();
    }
};
    </script>
</asp:Content>


What I have tried:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

public partial class Shopping_website_user_product_desc : System.Web.UI.Page
{
    private string connectionString = ConfigurationManager.ConnectionStrings["shoppingmaster"].ConnectionString;
    private int id;
    private int qty;
    private string product_name, product_desc, product_images;


    protected Label l1;
    protected Label l2;
    protected Button b1;
    protected Label t1;
    protected Label lblPrice;
    protected TextBox txtQuantity;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["id"] == null)
        {
            Response.Redirect("display_item.aspx");
        }
        else
        {
            id = Convert.ToInt32(Request.QueryString["id"]);

            if (!IsPostBack)
            {
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "SELECT * FROM product WHERE id = @id";
                    cmd.Parameters.AddWithValue("@id", id);

                    SqlDataReader reader = cmd.ExecuteReader();

                    if (reader.Read())
                    {
                        product_name = reader["product_name"].ToString();
                        product_desc = reader["product_desc"].ToString();
                        product_images = reader["product_images"].ToString();
                    }

                    reader.Close();

                    DataTable dt = new DataTable();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dt);

                    d1.DataSource = dt;
                    d1.DataBind();

                    con.Close();
                }
            }
           
        


        qty = get_qty(id);

                    if (qty == 0)
                    {
                        l2.Visible = false;
                        txtQuantity.Visible = false;
                        b1.Visible = false;
                        l1.Text = "There is no available quantity of this item.";
                    }
                    // Loop through the items in the Repeater
                    foreach (RepeaterItem item in d1.Items)
                    {
                        TextBox txtQuantity = (TextBox)item.FindControl("t1");
                        if (txtQuantity != null)
                        {
                            if (IsPostBack)
                            {
                                int product_qty = Convert.ToInt32(txtQuantity.Text);
                                txtQuantity.Text = product_qty.ToString();
                            }
                            else
                            {
                                txtQuantity.Text = "1"; // Set a default value if needed
                            }
                        }
                    }
                }
        }
    

    protected void btnMinus_Click(object sender, EventArgs e)
    {
        Button btnMinus = (Button)sender;
        RepeaterItem item = (RepeaterItem)btnMinus.NamingContainer;
        TextBox t1 = (TextBox)item.FindControl("t1");

        int product_qty = Convert.ToInt32(t1.Text);
        if (product_qty > 1)
        {
            product_qty--;
            t1.Text = product_qty.ToString();
        }
    }
    protected void btnPlus_Click(object sender, EventArgs e)
    {
        Button btnPlus = (Button)sender;
        RepeaterItem item = (RepeaterItem)btnPlus.NamingContainer;
        TextBox t1 = (TextBox)item.FindControl("t1");

        int product_qty = Convert.ToInt32(t1.Text);
        product_qty++;
        t1.Text = product_qty.ToString();
    }
    private bool UserLoggedIn()
    {
        // Check if the user is logged in
        // Return true if logged in, false otherwise

        // For example, you can check if a user session exists:
        return Session["user"] != null;
    }

    protected void b1_Click(object sender, EventArgs e)
    {
        if (!UserLoggedIn())
        {
            // User is not logged in, redirect to the login page
            Response.Redirect("login.aspx?returnUrl=product_desc.aspx?id=" + id);
            return;
        }

        using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();
            RepeaterItem item = (RepeaterItem)((Button)sender).NamingContainer;
            TextBox t1 = (TextBox)item.FindControl("t1");

            if (t1 != null && !string.IsNullOrEmpty(t1.Text))
            {
                int product_qty;
                if (int.TryParse(t1.Text, out product_qty))
                {
                    double product_price = GetProductPrice(id);

                    if (product_price == 0)
                    {
                        // Product price not found, handle the error
                        lblPrice.Text = "Error: Product price not found.";
                        return;
                    }

                    double totalPrice = product_price * product_qty;
                    double taxAmount = totalPrice * 0.15;
                    totalPrice += taxAmount;

                    if (lblPrice != null)
                    {
                        lblPrice.Text = "Total Price (including 15% tax): " + totalPrice.ToString("C2");
                    }

                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "SELECT * FROM registration WHERE email=@email";
                    cmd.Parameters.AddWithValue("@email", Session["user"]);
                    SqlDataReader dr = cmd.ExecuteReader();

                    if (dr.Read())
                    {
                        string firstname = dr["firstname"].ToString();
                        string lastname = dr["lastname"].ToString();
                        string email = dr["email"].ToString();
                        string address = dr["address"].ToString();
                        string city = dr["city"].ToString();
                        string state = dr["state"].ToString();
                        string pincode = dr["pincode"].ToString();
                        string mobile = dr["mobile"].ToString();
                        string product_name = this.product_name; // Assign the product name from the class variable
                        string product_images = this.product_images; // Assign the product images from the class variable

                        if (!string.IsNullOrEmpty(product_name) && !string.IsNullOrEmpty(product_images))
                        {
                            SqlCommand cmd3 = con.CreateCommand();
                            cmd3.CommandType = CommandType.Text;
                            cmd3.CommandText = "INSERT INTO orders (firstname, lastname, email, address, city, state, pincode, mobile, DateOfOrder, payment_status, product_id, product_name, product_price, product_qty, total_price, product_images) " +
                                              "VALUES (@firstname, @lastname, @email, @address, @city, @state, @pincode, @mobile, @DateOfOrder, @payment_status, @product_id, @product_name, @product_price, @product_qty, @total_price, @product_images)";

                            cmd3.Parameters.AddWithValue("@firstname", firstname);
                            cmd3.Parameters.AddWithValue("@lastname", lastname);
                            cmd3.Parameters.AddWithValue("@email", email);
                            cmd3.Parameters.AddWithValue("@address", address);
                            cmd3.Parameters.AddWithValue("@city", city);
                            cmd3.Parameters.AddWithValue("@state", state);
                            cmd3.Parameters.AddWithValue("@pincode", pincode);
                            cmd3.Parameters.AddWithValue("@mobile", mobile);
                            cmd3.Parameters.AddWithValue("@DateOfOrder", DateTime.Now);
                            cmd3.Parameters.AddWithValue("@payment_status", "Pending");
                            cmd3.Parameters.AddWithValue("@product_id", id);
                            cmd3.Parameters.AddWithValue("@product_name", product_name);
                            cmd3.Parameters.AddWithValue("@product_price", product_price);
                            cmd3.Parameters.AddWithValue("@product_qty", product_qty);
                            cmd3.Parameters.AddWithValue("@total_price", totalPrice);
                            cmd3.Parameters.AddWithValue("@product_images", product_images);
                            cmd3.ExecuteNonQuery();
                        }

                        else
                        {
                            dr.Close();
                        }

                        // ...

                        // Update the product quantity
                        SqlCommand cmd1 = con.CreateCommand();
                        cmd1.CommandType = CommandType.Text;
                        cmd1.CommandText = "UPDATE product SET product_qty = product_qty - @quantity WHERE id = @id";
                        cmd1.Parameters.AddWithValue("@quantity", product_qty);
                        cmd1.Parameters.AddWithValue("@id", id);
                        cmd1.ExecuteNonQuery();

                        // Retrieve the last inserted order ID
                        int orderId = GetLastInsertedOrderId();

                        // Add the item to the cookie
                        if (Request.Cookies["aa"] == null)
                        {
                            Response.Cookies["aa"].Value = product_name + "," + product_desc + "," + product_price + "," + product_qty + "," + product_images + "," + id + "," + orderId;
                            Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);
                        }
                        else
                        {
                            Response.Cookies["aa"].Value = Request.Cookies["aa"].Value + "|" + product_name + "," + product_desc + "," + product_price + "," + product_qty + "," + product_images + "," + id + "," + orderId;
                            Response.Cookies["aa"].Expires = DateTime.Now.AddDays(1);
                        }
                    }
                }
            }
        }
    }

            public int get_qty(int id)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                con.Open();

                SqlCommand cmd = con.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT product_qty FROM product WHERE id=@id";
                cmd.Parameters.AddWithValue("@id", id);
                SqlDataReader dr = cmd.ExecuteReader();

                if (dr.Read())
                {
                    qty = Convert.ToInt32(dr["product_qty"]);
                }

                dr.Close();
            }

            return qty;
        }

        public int GetLastInsertedOrderId()
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                con.Open();

                SqlCommand cmd = con.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT TOP 1 Id FROM orders ORDER BY Id DESC";
                int orderId = Convert.ToInt32(cmd.ExecuteScalar());

                return orderId;
            }
        }

        public double GetProductPrice(int id)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                con.Open();

                SqlCommand cmd = con.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT product_price FROM product WHERE id=@id";
                cmd.Parameters.AddWithValue("@id", id);
                object result = cmd.ExecuteScalar();

                if (result != null && double.TryParse(result.ToString(), out double price))
                {
                    return price;
                }

                return 0;
            }
        }
 }
Posted

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