DropDownList dynamic generation method in C
- 2021-01-19 22:21:18
- OfStack
This article illustrates the dynamic DropDownList generation method in C#. Share with you for your reference. The specific analysis is as follows:
Today, I learned DropDownList dynamic generation and asp.net life cycle, and ViewState, because the project needs to dynamically generate conditions according to the requirements, so I studied a part of the code to complete these work, well, without more words, let's look at the code
First is the code of the web page:
<span style="font-size:18px;"><body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
//placeholder Control is equivalent to 1 A container for storing other controls
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button"/></div>
</form>
</body></span>
Here is the c# program
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)
// We can see 1 Under the asp The life cycle of
{
BindDrpClass();
}
protected void Page_Load(object sender, EventArgs e)
{
string str = "8/14/19/25";
// Database read
string[] arr = str.Split('/');
if (arr.Length == PlaceHolder1.Controls.Count)
// Prevent read errors when adding categories
{
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();
// Specific operations to add
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);
}
}
I hope this article is helpful to your C# program design.