Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
</form>
</body>
</html>
==============================================================================
Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Model;
using BLL;
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)
{
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);
}
}