C#中DropDownList动态生成的方法
本文实例讲述了C#中DropDownList动态生成的方法。分享给大家供大家参考。具体分析如下:
今天学习了DropDownList的动态生成以及asp.net的生命周期,还有ViewState,因为项目需要根据需求动态生成条件所以研究了一部分代码来完成这些工作,好了话不多说了,来看代码
首先是网页的代码:
<spanstyle="font-size:18px;"><body> <formid="form1"runat="server"> <div> <asp:PlaceHolderID="PlaceHolder1"runat="server"></asp:PlaceHolder> //placeholder控件相当于一个容器,用于存放其他控件 <br/> <asp:ButtonID="Button1"runat="server"OnClick="Button1_Click"Text="Button"/></div> </form> </body></span>
下面是c#程序
publicpartialclass_Default:System.Web.UI.Page { privateCategoryBLL_categoryBLL=newCategoryBLL(); privateCategory_category=newCategory(); privatevoidPage_Init(objectsender,System.EventArgse) //可以看一下asp的生命周期 { BindDrpClass(); } protectedvoidPage_Load(objectsender,EventArgse) { stringstr="8/14/19/25"; //数据库读取 string[]arr=str.Split('/'); if(arr.Length==PlaceHolder1.Controls.Count) //防止新增类别时读取出错 { for(inti=0;i<PlaceHolder1.Controls.Count;i++) { if(PlaceHolder1.Controls[i]isDropDownList) { ((DropDownList)PlaceHolder1.Controls[i]).SelectedValue=arr[i]; } } } } privatevoidBindDrpClass() { DataTabledt=_categoryBLL.GetCategory(); DataRow[]drs=dt.Select("pid=0"); foreach(DataRowdrindrs) { stringid=dr["id"].ToString(); stringname=dr["name"].ToString(); DropDownListddl=newDropDownList(); //具体添加的操作 ddl.Items.Clear(); ddl.ID="ddl"+id; ddl.Items.Add(newListItem("-"+name+"-",id)); PlaceHolder1.Controls.Add(ddl); intsonparentid=int.Parse(id); BindDrpNode(sonparentid,dt,ddl); } } privatevoidBindDrpNode(intparentid,DataTabledt,DropDownListddl) { DataRow[]drs=dt.Select("pid="+parentid); foreach(DataRowdrindrs) { stringid=dr["id"].ToString(); stringname=dr["name"].ToString(); ddl.Items.Add(newListItem(name,id)); PlaceHolder1.Controls.Add(ddl); } } protectedvoidButton1_Click(objectsender,EventArgse) { stringcategory=""; stringcategory2=""; foreach(ControlchildControlinPlaceHolder1.Controls) { if(childControlisDropDownList) { 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#程序设计有所帮助。