C#中DropDownList靜態生成的辦法。本站提示廣大學習愛好者:(C#中DropDownList靜態生成的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中DropDownList靜態生成的辦法正文
本文實例講述了C#中DropDownList靜態生成的辦法。分享給年夜家供年夜家參考。詳細剖析以下:
明天進修了DropDownList的靜態生成 和asp.net的性命周期,還有ViewState,由於項目須要依據需求靜態生成前提 所以研討了一部門代碼來完成這些任務,好了話不多說了,來看代碼
起首是網頁的代碼:
<span ><body> <form id="form1" runat="server"> <div> <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder> //placeholder控件相當於一個容器,用於寄存其他控件 <br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button"/></div> </form> </body></span>
上面是c#法式
public partial class _Default : System.Web.UI.Page { private CategoryBLL _categoryBLL = new CategoryBLL(); private Category _category = new Category(); private void Page_Init(object sender, System.EventArgs e) //可以看一下asp的性命周期 { BindDrpClass(); } protected void Page_Load(object sender, EventArgs e) { string str = "8/14/19/25"; //數據庫讀取 string[] arr = str.Split('/'); if (arr.Length == PlaceHolder1.Controls.Count) //避免新增種別時讀掏出錯 { for (int i = 0; i < PlaceHolder1.Controls.Count; i++) { if (PlaceHolder1.Controls[i] is DropDownList) { ((DropDownList)PlaceHolder1.Controls[i]).SelectedValue = arr[i]; } } } } private void BindDrpClass() { DataTable dt = _categoryBLL.GetCategory(); DataRow[] drs = dt.Select("pid=0"); foreach (DataRow dr in drs) { string id = dr["id"].ToString(); string name = dr["name"].ToString(); DropDownList ddl = new DropDownList(); //詳細添加的操作 ddl.Items.Clear(); ddl.ID = "ddl" + id; ddl.Items.Add(new ListItem("-" + name + "-", id)); PlaceHolder1.Controls.Add(ddl); int sonparentid = int.Parse(id); BindDrpNode(sonparentid, dt, ddl); } } private void BindDrpNode(int parentid, DataTable dt, DropDownList ddl) { DataRow[] drs = dt.Select("pid= " + parentid); foreach (DataRow dr in drs) { string id = dr["id"].ToString(); string name = dr["name"].ToString(); ddl.Items.Add(new ListItem(name, id)); PlaceHolder1.Controls.Add(ddl); } } protected void Button1_Click(object sender, EventArgs e) { string category = ""; string category2 = ""; foreach (Control childControl in PlaceHolder1.Controls) { if (childControl is DropDownList) { category += "/" + ((DropDownList)childControl).SelectedItem.Text; category2 += "/" + ((DropDownList)childControl).SelectedValue; } } if (category.Length > 0) category = category.Remove(0, 1); Response.Write(category); Response.Write("<br />"); if (category2.Length > 0) category2 = category2.Remove(0, 1); Response.Write(category2); } }
願望本文所述對年夜家的C#法式設計有所贊助。