欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中DropDownList动态生成的方法

程序员文章站 2023-12-12 14:54:28
本文实例讲述了c#中dropdownlist动态生成的方法。分享给大家供大家参考。具体分析如下: 今天学习了dropdownlist的动态生成 以及asp.net的生命周...

本文实例讲述了c#中dropdownlist动态生成的方法。分享给大家供大家参考。具体分析如下:

今天学习了dropdownlist的动态生成 以及asp.net的生命周期,还有viewstate,因为项目需要根据需求动态生成条件 所以研究了一部分代码来完成这些工作,好了话不多说了,来看代码

首先是网页的代码:

<span style="font-size:18px;"><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#程序设计有所帮助。

上一篇:

下一篇: