所以我几乎有这个工作。我根据用户选择创建动态列表框。当用户第一次加载页面时,总是只有一个 ListBox 显示顶级类别(没有父类别的)。我有带有子类别的类别。可以是很多子类别,像这样
猫 1
猫 2
猫 2.1
猫 2.2
-- Cat 2.2.1 --- Cat 2.2.1.1
等等。
如果用户从已显示的列表框中选择一个值,我遇到的问题是清除列表框。因此,如果显示了 4 个列表框并且用户从第一个列表框中选择了一个新值,该值显示没有父级的顶部撕裂类别,则所有列表框都应该消失并且新的列表框应该出现。如果有 4 个 Listboxes 并且用户单击 ListbOx 3 中的新项目,则第 4 个应该将子类别重新呈现给其选定的父项。我希望我能正确地解释自己。
到目前为止,这是我的代码: public partial class WebForm2 : System.Web.UI.Page { private Int32 controlCount = 0; 面板_panel;
private Panel PanelPlaceholder
{
get
{
if (_panel == null && Master != null)
_panel = pnlContainer;
return _panel;
}
}
protected void Page_PreInit(Object sender, EventArgs e)
{
this.EnsureChildControls();
if (IsPostBack)
{
// Re-create controls but not from datasource
// The controlCount value is output in the page as a hidden field during PreRender.
controlCount = Int32.Parse(Request.Form["controlCount"]); // assigns control count from persistence medium (hidden field)
for (Int32 i = 0; i < controlCount; i++)
{
CreateDynamicControlGroup(false);
}
}
}
protected void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
int cc = controlCount;
DataTable dt = null;
Dictionary<string, string> Params = new Dictionary<string, string>();
dt = Globals.g_DatabaseHandler.GetRecords(StoredProcedures.GetMainCategories, Params);
CreateDynamicControlGroup(true);
ListBox lb = (ListBox)PanelPlaceholder.Controls[controlCount - 1];
lb.DataSource = dt;
lb.DataValueField = "ID";
lb.DataTextField = "Name";
lb.DataBind();
}
}
protected void Page_PreRender(Object sender, EventArgs e)
{
// persist control count
ClientScript.RegisterHiddenField("controlCount", controlCount.ToString());
}
private void ListBox_SelectedIndexChanged(Object sender, EventArgs e)
{
ListBox lb = sender as ListBox;
Dictionary<string, string> Params = new Dictionary<string, string>();
Params.Add("parentID", lb.SelectedValue);
DataTable Categories = Globals.g_DatabaseHandler.GetRecords(StoredProcedures.GetChildCategories, Params);
if (Categories.Rows.Count > 0)
{
CreateDynamicControlGroup(true);
ListBox newLb = (ListBox)PanelPlaceholder.Controls[controlCount - 1];
newLb.DataSource = Categories; // use the same table
newLb.DataValueField = "ID";
newLb.DataTextField = "Name";
newLb.DataBind();
}
}
private void CreateDynamicControlGroup(Boolean incrementCounter)
{
// Create one logical set of controls do not assign values!
ListBox lb = new ListBox();
lb.AutoPostBack = true;
lb.CssClass = "panel";
PanelPlaceholder.Controls.Add(lb);
// wire event delegate
lb.SelectedIndexChanged += new EventHandler(ListBox_SelectedIndexChanged);
if (incrementCounter)
{
controlCount += 1;
}
}
}
这是我的标记:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div class="Column12" id="Form_NewListing">
<h2 class="h2row">Create Your Listing - Step 1 of 2)</h2>
<h3 class="h3row">Select a category</h3>
<div class="panel">
<asp:Panel ID="pnlContainer" runat="server"></asp:Panel>
</div>
</div>
提前致谢。