C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#中DropDownList动态生成

C#中DropDownList动态生成的方法

作者:小啊斌

这篇文章主要介绍了C#中DropDownList动态生成的方法,实例分析了C#中DropDownList的使用技巧,非常具有实用价值,需要的朋友可以参考下

本文实例讲述了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#程序设计有所帮助。

您可能感兴趣的文章:
阅读全文