■ DropDownList 클래스를 사용해 동적으로 생성하는 방법을 보여준다.
▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!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="form" runat="server"> <div> <asp:PlaceHolder ID="placeHolder" runat="server" /> <hr /> <asp:Button ID="getValueButton" runat="server" Text="값 구하기" OnClick="getValueButton_Click" /> <hr /> <asp:Label ID="messageLabel" runat="server" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
using System; using System.Web.UI; using System.Web.UI.WebControls; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { for(int i = 1; i <= 2; i++) { DropDownList dropDownList = new DropDownList(); dropDownList.ID = string.Format("dropDownList{0}", i); dropDownList.Items.Add(new ListItem("Text1", "Value1")); dropDownList.Items.Add(new ListItem("Text2", "Value2")); dropDownList.Items.Add(new ListItem("Text3", "Value3")); this.placeHolder.Controls.Add(dropDownList); } } #endregion #region 값 구하기 버튼 클릭시 처리하기 - getValueButton_Click(sender, e) /// <summary> /// 값 구하기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void getValueButton_Click(object sender, EventArgs e) { this.messageLabel.Text = "선택된 값 : "; for(int i = 1; i <= 2; i++) { DropDownList dropDownList = this.placeHolder.FindControl(String.Format("dropDownList{0}", i)) as DropDownList; if(dropDownList != null) { this.messageLabel.Text += dropDownList.SelectedValue + ", "; } } } #endregion } } |