Write an ASP.Net application to create a user control that contains a list of colors. Add a button to the Web Form which, when clicked, changes the color of the form to the color selected from the list

Answer

Here’s an ASP.NET Web Forms application that includes:

  1. A User Control (ColorPicker.ascx) containing a DropDownList with color options.
  2. A Web Form (Default.aspx) with a Button that changes the background color based on the selected color.

Steps to Implement

  1. Create a Web Forms Application in Visual Studio.
  2. Add a User Control (ColorPicker.ascx).
  3. Add a Web Form (Default.aspx).
  4. Copy the following code into the respective files.

1. Create the User Control (ColorPicker.ascx)

Right-click the project > Add > New Item > Web User Control > Name it ColorPicker.ascx.

ColorPicker.ascx

<%@ Control Language="VB" AutoEventWireup="true" CodeBehind="ColorPicker.ascx.vb" Inherits="YourNamespace.ColorPicker" %>

<asp:DropDownList ID="ddlColors" runat="server">
    <asp:ListItem Text="Red" Value="Red"></asp:ListItem>
    <asp:ListItem Text="Green" Value="Green"></asp:ListItem>
    <asp:ListItem Text="Blue" Value="Blue"></asp:ListItem>
    <asp:ListItem Text="Yellow" Value="Yellow"></asp:ListItem>
    <asp:ListItem Text="Cyan" Value="Cyan"></asp:ListItem>
</asp:DropDownList>

2. Code-Behind for the User Control (ColorPicker.ascx.vb)

Public Class ColorPicker
    Inherits System.Web.UI.UserControl

    Public ReadOnly Property SelectedColor As String
        Get
            Return ddlColors.SelectedValue
        End Get
    End Property
End Class

3. Create the Web Form (Default.aspx)

Replace YourNamespace with the actual namespace of your project.

Default.aspx

<%@ Page Language="VB" AutoEventWireup="true" CodeBehind="Default.aspx.vb" Inherits="YourNamespace.Default" %>
<%@ Register Src="ColorPicker.ascx" TagPrefix="uc" TagName="ColorPicker" %>

<!DOCTYPE html>
<html lang="en">
<head runat="server">
    <title>Color Picker</title>
</head>
<body runat="server" id="bodyTag">
    <form id="form1" runat="server">
        <uc:ColorPicker ID="ColorPicker1" runat="server" />
        <asp:Button ID="btnChangeColor" runat="server" Text="Change Color" OnClick="btnChangeColor_Click" />
    </form>
</body>
</html>

4. Code-Behind for the Web Form (Default.aspx.vb)

Public Class Default
    Inherits System.Web.UI.Page

    Protected Sub btnChangeColor_Click(sender As Object, e As EventArgs)
        bodyTag.Style("background-color") = ColorPicker1.SelectedColor
    End Sub
End Class

How It Works

  1. The user control (ColorPicker.ascx) has a dropdown list with color options.
  2. The main web form (Default.aspx) includes the user control and a button.
  3. When the button is clicked, the background color of the page changes to the selected color.
Scroll to Top