Practical-12
Problem Statement
Write a program to set Image on Image Control according to the selection of the image name from the dropdown list.
Solution
To set an image on an Image Control according to the selection of the image name from the dropdown list in ASP.NET, follow the steps below:
- Create a new ASP.NET Web Application project in Visual Studio.
- Add a new Web Form to the project by right-clicking on the project in the Solution Explorer, selecting "Add" > "Web Form".
- Rename the Web Form to "Default.aspx".
- Open the "Default.aspx" file and design the user interface as per your requirements using HTML and ASP.NET controls.
- Add the following controls to the "Default.aspx" form:
- DropDownList control:
<asp:DropDownList ID="ddlImages" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlImages_SelectedIndexChanged"></asp:DropDownList> - Image control:
<asp:Image ID="imgSelectedImage" runat="server"></asp:Image>
- DropDownList control:
- In the code-behind file, write the following code in the Page_Load event handler to populate the DropDownList control:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlImages.Items.Add(new ListItem("Image 1", "1"));
ddlImages.Items.Add(new ListItem("Image 2", "2"));
ddlImages.Items.Add(new ListItem("Image 3", "3"));
}
}
- Write the following code in the SelectedIndexChanged event handler of the DropDownList control to set the selected image on the Image control:
protected void ddlImages_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedImage = ddlImages.SelectedItem.Text;
imgSelectedImage.ImageUrl = $"~/Images/{selectedImage}.jpg";
}
- Create a folder named "Images" in the root directory of your project.
- Add the images you want to display to the "Images" folder.
- Build and run the application to see the image selection in action.
This completes the solution for setting an image on an Image Control according to the selection of the image name from the dropdown list.