Write an ASP.Net program containing the following controls: ListBox, Button, Image, Label. The ListBox is used to list items available in a store. When the user clicks on an item in the ListBox, its image is displayed in the Image control. When the user clicks the Button, the cost of the selected item is displayed in the Label control.

Answer:

Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="YourNamespace._Default" %>

<!DOCTYPE html>
<html>
<head runat="server">
    <title>Store</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h2>Welcome to the Store</h2>

            <label for="lstItems">Select an item:</label>
            <asp:ListBox ID="lstItems" runat="server" AutoPostBack="True" OnSelectedIndexChanged="lstItems_SelectedIndexChanged">
                <asp:ListItem Text="Laptop" Value="1" />
                <asp:ListItem Text="Smartphone" Value="2" />
                <asp:ListItem Text="Headphones" Value="3" />
            </asp:ListBox>

            <br />

            <asp:Image ID="imgProduct" runat="server" Width="200px" Height="200px" />

            <br />

            <asp:Button ID="btnShowCost" runat="server" Text="Show Cost" OnClick="btnShowCost_Click" />

            <br />

            <asp:Label ID="lblCost" runat="server" ForeColor="Blue"></asp:Label>
        </div>
    </form>
</body>
</html>

Default.aspx.cs:

using System;

namespace YourNamespace
{
    public partial class _Default : System.Web.UI.Page
    {
        private readonly Dictionary<string, (string imageUrl, double cost)> storeItems = new Dictionary<string, (string, double)>
        {
            { "Laptop", ("~/Images/laptop.jpg", 999.99) },
            { "Smartphone", ("~/Images/smartphone.jpg", 499.99) },
            { "Headphones", ("~/Images/headphones.jpg", 199.99) }
        };

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void lstItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedItem = lstItems.SelectedItem.Text;

            if (storeItems.ContainsKey(selectedItem))
            {
                imgProduct.ImageUrl = storeItems[selectedItem].imageUrl;
            }
        }

        protected void btnShowCost_Click(object sender, EventArgs e)
        {
            string selectedItem = lstItems.SelectedItem?.Text;

            if (!string.IsNullOrEmpty(selectedItem) && storeItems.ContainsKey(selectedItem))
            {
                double cost = storeItems[selectedItem].cost;
                lblCost.Text = $"The cost of {selectedItem} is ${cost:F2}.";
            }
            else
            {
                lblCost.Text = "Please select an item.";
            }
        }
    }
}
Scroll to Top