'Dynamically displaying price of product in shop

I built a shop in my .NET project which makes use of the DataList control, to present each item and allow to add it in a certain size and amount to the shopping cart. I would like to dynamically show the price of the product according the size selected in the DropDownList "SizeDDL" and the amount specified in the TextBox "AmountTxtEdit". Each product has a price according to it's size, for example a product with ID 1 size 37 can be 589.99$, and the same product size 38 can be 459.99$. The price for each product and size is saved in the database in the table I have attached. I attached my code for the page, and would appreciate any ideas for how to display the price. If anything is unclear or wrong with my code, please let me know.

                        <form id="form1" runat="server">
                            <div class="align-center">
                                <asp:Button ID="ShoppingCartButton" runat="server" OnClick="ShoppingCartButton_Click" Text="View Shopping Cart" />
                                <br />
                                <br />
                                <asp:Label ID="ErrorLbl" runat="server" Visible="false"></asp:Label>
                            </div>
                            <asp:DataList ID="ShopDataList" runat="server" RepeatDirection="Horizontal" RepeatLayout="Table" RepeatColumns="3" DataKeyField="productId" OnEditCommand="Edit_Command" OnCancelCommand="Cancel_Command" OnUpdateCommand="Buy_Command">
                                <ItemStyle BackColor="LightYellow" BorderWidth="50" BorderColor="White"/>
                                <AlternatingItemStyle BackColor="LightBlue" />
                                <ItemTemplate>
                                    <asp:TextBox ID="ProductIdTxt" Visible="false" runat="server" ReadOnly="true" Text='<%# Eval("productId") %>'></asp:TextBox>
                                    <asp:Image ID="ImageBox" runat="server" ImageUrl='<%# "~/productImages/" + Eval("imageName") %>' Height="250" Width="250"/>
                                    <br />
                                    <h3>Product Name:&nbsp</h3>
                                    <asp:TextBox ID="ProductNameTxt" runat="server" Text='<%# Eval("name") %>' ReadOnly="true"></asp:TextBox>
                                    <br />
                                    <h3>Product Company:&nbsp</h3>
                                    <asp:TextBox ID="CompanyTxt" runat="server" Text='<%# Eval("company") %>' ReadOnly="true"></asp:TextBox>
                                    <br />
                                    <h3>Size:&nbsp</h3>
                                    <asp:TextBox ID="SizeTxt" runat="server" Text='Select A Size' ReadOnly="true"></asp:TextBox>
                                    <br />
                                    <h3>Amount:&nbsp</h3>
                                    <asp:TextBox ID="AmountTxt" runat="server" Text='Select An Amount' ReadOnly="true"></asp:TextBox>
                                    <br />
                                    <div class="align-center">
                                        <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" CssClass="button shopbutton" CausesValidation="false" />
                                    </div>
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="ProductIdTxt" Visible="false" runat="server" ReadOnly="true" Text='<%# Eval("productId") %>'></asp:TextBox>
                                    <asp:Image ID="ImageBox" runat="server" ImageUrl='<%# "~/productImages/" + Eval("imageName") %>' Height="250" Width="250"/>
                                    <br />
                                    <h3>Product Name:&nbsp</h3>
                                    <asp:TextBox ID="ProductNameTxtEdit" runat="server" Text='<%# Eval("name") %>' ReadOnly="true"></asp:TextBox>
                                    <br />
                                    <h3>Product Company:&nbsp</h3>
                                    <asp:TextBox ID="CompanyTxtEdit" runat="server" Text='<%# Eval("company") %>' ReadOnly="true"></asp:TextBox>
                                    <br />
                                    <h3>Size:&nbsp</h3> 
                                    <asp:DropDownList ID="SizeDDL" runat="server" DataSource='<%# FillDDL((int)Eval("productId")) %>'></asp:DropDownList>
                                    <br />
                                    <h3>Amount:&nbsp</h3>
                                    <asp:TextBox ID="AmountTxtEdit" runat="server" Text='0'></asp:TextBox>
                                    <asp:RequiredFieldValidator ControlToValidate="AmountTxtEdit" Display="None" ID="RequiredFieldValidator2" runat="server" ErrorMessage="Amount is required"></asp:RequiredFieldValidator>
                                    <asp:RegularExpressionValidator ValidationExpression="^([1-9]|10)$" ControlToValidate="AmountTxtEdit" Display="None" ID="RegularExpressionValidator1" runat="server" ErrorMessage="Invalid amount! Must be between 1 and 10"></asp:RegularExpressionValidator>
                                    <br />
                                    <div class="align-center">
                                        <asp:Button ID="BuyButton" runat="server" CommandName="Update" Text="Add To Cart" CssClass="button shopbutton" CausesValidation="true"/>
                                    </div>
                                    <br />
                                    <div class="align-center">
                                        <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" CssClass="button shopbutton" CausesValidation="false"/>
                                    </div>
                                    <asp:ValidationSummary ID="SummaryValidator" runat="server" ShowMessageBox="true" ShowSummary="false" />
                                </EditItemTemplate>
                            </asp:DataList>
                        </form>

CodeBehind:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class ClimbingShop : System.Web.UI.Page
{
    public string priceStr = "";
    string[] priceArr;
    public string ddl = "";
    public DataTable productDt,
        supplyDt; //שומר את הנתונים המוחזרים על ידי האחסון
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["username"] == null)//בודק אם המשתמש רשום
            Response.Redirect("NoAccessPage.aspx"); //מעביר את המשתמש לדף האין כניסה

        if(Session["cartStatus"] != null)
        {
            switch (Session["cartStatus"].ToString())
            {
                case "empty":
                    {
                        ErrorLbl.Text = "<h3 class='red'>Your cart is empty!</h3>";
                        ErrorLbl.Visible = true;
                        Session["cartStatus"] = null;
                        break;
                    }
                case "bought":
                    {
                        ErrorLbl.Text = "<h3 class='green'>Thank you for your purchase! A receipt has been sent to your email!</h3>";
                        ErrorLbl.Visible = true;
                        Session["cartStatus"] = null;
                        break;
                    }
                case "error":
                    {
                        ErrorLbl.Text = "<h3 class='red'>There seems to have been an error! Maybe the admins changed something</h3>";
                        ErrorLbl.Visible = true;
                        Session["cartStatus"] = null;
                        break;
                    }
            }
        }

        if (!IsPostBack)
        {
            GetData();
        }
    }

    public void GetData()
    {
        productDt = MyAdoHelper.GetProductTbl();
        supplyDt = MyAdoHelper.GetSupplyTbl();

        if (productDt == null || supplyDt == null)
            Response.Redirect("NoAccessPage.aspx");
        ShopDataList.DataSource = productDt;
        ShopDataList.DataBind();
    }

    protected void GenerateSizeDDL(int productId)
    {
        ddl = "";

        DataTable sizeDt = MyAdoHelper.ExecuteDataTable("MyDatabase.mdf", "SELECT size FROM tblSupply WHERE productId=" + productId);
        //Change to SP later on

        foreach (DataRow dtRow in sizeDt.Rows)
        {
            ddl += "<option value='" + dtRow[0].ToString() + "'>" + dtRow[0].ToString() + "</option>";
        }
    }

    protected void ShoppingCartButton_Click(object sender, EventArgs e)
    {
        if (MyAdoHelper.IsExist("MyDatabase.mdf", "SELECT * FROM tblOrder WHERE username='" + Session["username"].ToString() + "' AND paid='0'"))
        {
            Response.Redirect("ShoppingCart.aspx");
        }
        else
        {
            ErrorLbl.Text = "<h3 class='red'>Your cart is empty!</h3>";
            ErrorLbl.Visible = true;
        }
    }

    protected void Edit_Command(object sender, DataListCommandEventArgs e)
    {
        ShopDataList.EditItemIndex = e.Item.ItemIndex;

        int editProductId = int.Parse(((TextBox)e.Item.FindControl("ProductIdTxt")).Text);

        GetData();
    }

    public ArrayList FillDDL(int productId)
    {
        DataTable sizeDt = MyAdoHelper.ExecuteDataTable("MyDatabase.mdf", "SELECT size FROM tblSupply WHERE productId=" + productId);
        ArrayList values = new ArrayList();
        
        foreach(DataRow dataRow in sizeDt.Rows)
        {
            values.Add(dataRow["size"]);
        }

        return values;
    }

    protected void Cancel_Command(object source, DataListCommandEventArgs e)
    {
        ShopDataList.EditItemIndex = -1;
        GetData();
    }

    protected void Buy_Command(object source, DataListCommandEventArgs e)
    {
        int productId = int.Parse(((TextBox)e.Item.FindControl("ProductIdTxt")).Text),
            amount = int.Parse(((TextBox)e.Item.FindControl("AmountTxtEdit")).Text);
        int size = int.Parse(((DropDownList)e.Item.FindControl("SizeDDL")).SelectedValue);

        if(!MyAdoHelper.IsExist("MyDatabase.mdf", "SELECT * FROM tblSupply WHERE productId='" + productId + "' AND size='" + size + "'"))
        {
            Session["cartStatus"] = "error";
            Response.Redirect("ClimbingShop.aspx");
        }

        if (MyAdoHelper.IsExist("MyDatabase.mdf", "SELECT * FROM tblOrder WHERE username='" + Session["username"].ToString() + "' AND paid='0'"))
        {
            DataTable orderTbl = MyAdoHelper.ExecuteDataTable("MyDatabase.mdf", "SELECT * FROM tblOrder WHERE username='" + Session["username"].ToString() + "' AND paid='0'");
            int orderId = int.Parse(orderTbl.Rows[0][0].ToString());
            if (MyAdoHelper.IsExist("MyDatabase.mdf", "SELECT * FROM tblOrderProduct WHERE orderId='" + orderId + "' AND productId='" + productId + "' AND size='" + size + "'"))
            {
                MyAdoHelper.ExecuteNonQuery("MyDatabase.mdf", "UPDATE tblOrderProduct SET amount=amount+" + amount + " WHERE orderId='" + orderId + "' AND productId='" + productId + "' AND size='" + size + "'");
            }
            else
            {
                MyAdoHelper.ExecuteNonQuery("MyDatabase.mdf", "INSERT INTO tblOrderProduct(orderId, productId, size, amount) VALUES ('" + orderId + "', '" + productId + "', '" + size + "', '" + amount + "')");
            }
        }
        else
        {
            DateTime myDateTime = DateTime.UtcNow;
            string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
            MyAdoHelper.ExecuteNonQuery("MyDatabase.mdf", "INSERT INTO tblOrder (username, datetime, paid) VALUES ('" + Session["username"].ToString() + "', '" + sqlFormattedDate + "', '0')");
            DataTable orderTbl = MyAdoHelper.ExecuteDataTable("MyDatabase.mdf", "SELECT * FROM tblOrder WHERE username='" + Session["username"].ToString() + "' AND paid='0'");
            int newOrderId = int.Parse(orderTbl.Rows[0][0].ToString());
            MyAdoHelper.ExecuteNonQuery("MyDatabase.mdf", "INSERT INTO tblOrderProduct (orderId, productId, size, amount) VALUES ('" + newOrderId + "', '" + productId + "', '" + size + "', '" + amount + "')");
        }
        ShopDataList.EditItemIndex = -1;
        GetData();
    }

    protected void Size_ServerChange(object sender, EventArgs e)
    {
        //General idea: use current editing productId to locate item, then use item to find selected size, or use parameter when calling function for size. Then use size and productId to identify price, then update price textbox and refresh the textbox only, not the entire page.
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source