제목 : 동적으로 DropDownList 생성 및 선택된 값 가져오기
[FrmDropDownListDynamicCreation.aspx]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FrmDropDownListDynamicCreation.aspx.cs" Inherits="FrmDropDownListDynamicCreation" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>동적으로 DropDownList 생성 및 선택된 값 가져오기</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<hr />
<asp:Button ID="btnGet" runat="server" Text="값 가져오기" OnClick="btnGet_Click" />
<hr />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
[FrmDropDownListDynamicCreation.aspx.cs]
using System;
using System.Web.UI.WebControls;
public partial class FrmDropDownListDynamicCreation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 1; i <= 2; i++)
{
DropDownList ddl = new DropDownList();
ddl.ID = String.Format("ddl{0}", i); // ddl1, ddl2
ddl.Items.Add(new ListItem("Text1", "Value1"));
ddl.Items.Add(new ListItem("Text2", "Value2"));
ddl.Items.Add(new ListItem("Text3", "Value3"));
PlaceHolder1.Controls.Add(ddl); // 동적으로 생성된 드롭다운리스트 추가
}
}
protected void btnGet_Click(object sender, EventArgs e)
{
Label1.Text = "선택된 값: ";
for (int i = 1; i <= 2; i++)
{
DropDownList ddl = PlaceHolder1.FindControl(String.Format("ddl{0}", i)) as DropDownList;
if (ddl != null)
{
Label1.Text += ddl.SelectedValue + ", ";
}
}
}
}