June 16, 2009

Dynamically Create DropDownList

In this article, I will dynamically create a DropDownList and add it to a page. I will also set the AutoPostBack property to true and get the selected value of the DropDownList to the page.

At first, I will create the .aspx page. The code is below.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplicationPrac._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Label ID="Label1" runat="server" Text="" />
</form>
</body>
</html>


In the page, I added Panel control where the DropDownList control will be added. There is also a Label control that will hold the value of the DropDownList control's selected value.

In the code behind for the page, I am creating a method that creates the DropDownList, adds an event handler to the control and then the method is being called from the Page_Load method.

private DropDownList CreateDropDown()
{
DropDownList dl = new DropDownList();
dl.Items.Add("A");
dl.Items.Add("B");
dl.Items.Add("C");
dl.Items.Add("D");

dl.AutoPostBack = true;
dl.SelectedIndexChanged +=new EventHandler(dl_SelectedIndexChanged);
return dl;
}


In this method, I create a DropDownList, add a few items, set the AutoPostBack property to true and then add a OnSelectedIndexChanged event.

protected void dl_SelectedIndexChanged(object sender, EventArgs arg)
{
Label1.Text = ((DropDownList)sender).SelectedValue;
}


Then, the last thing is to add the DropDownList method on the Page_Load method. Since the DropDownList is dynamically created the control needs to be added to Page each time the Page loads.

protected void Page_Load(object sender, EventArgs e)
{
Panel1.Controls.Add(CreateDropDown());
}


0 comments:

Reference: Shahed Kazi at AspNetify.com