我在带有代码的母版页的网络表单中有一个 PlaceHolder
<asp:DropDownList ID="NoofSubjectList" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="NoofSubject_Index_Changed">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
</asp:DropDownList>
<asp:PlaceHolder ID="placeholder" runat="server" />
根据从DropDownList (1)中选择的数字 ( n ) ,我将为所选的 n 数字动态创建两组DropDownList (2,3)。其中第一个DropDownList 从数据库加载数据。代码如下所示,
protected void NoofSubject_Index_Changed(Object sender, EventArgs e)
{
int value = Convert.ToInt32(NoofSubjectList.SelectedItem.Text.ToString());
DataSet ds1 = new DataSet();
MySql.Data.MySqlClient.MySqlConnection mysqlConnection = new
MySql.Data.MySqlClient.MySqlConnection
("Database=school;Server=localhost;UID=root;PWD=;");
MySql.Data.MySqlClient.MySqlCommand mysqlCommand = new
MySql.Data.MySqlClient.MySqlCommand
("SELECT Dept FROM tabledept WHERE Status='Active'", mysqlConnection);
MySql.Data.MySqlClient.MySqlDataAdapter mysqlAdaptor = new
MySql.Data.MySqlClient.MySqlDataAdapter(mysqlCommand);
mysqlAdaptor.Fill(ds1);
for (int i = 0; i <= value - 1; i++)
{
DropDownList _SubList = new DropDownList();
_SubList.ID = "SubList" + (i + 1);
_SubList.Width= 75;
DropDownList _DeptList = new DropDownList();
_DeptList.ID = "DeptList" + (i + 1);
_DeptList.Width = 75;
_DeptList.SelectedIndexChanged += DeptList_Index_Changed;
Literal _spacer = new Literal();
_spacer.Text = "<br />";
Literal _spacerlbl = new Literal();
_spacerlbl.Text = " ";
Label _Lbl = new Label();
_Lbl.ID = "lbl_Subject" + i;
_Lbl.Text = "Subject" + (i+1);
Label _Lbl1 = new Label();
_Lbl1.ID = "lbl_Dept" + i;
_Lbl1.Text = "Department";
_DeptList.DataSource = ds1;
_DeptList.DataTextField = ds1.Tables[0].Columns["Dept"].ColumnName;
_DeptList.DataValueField = ds1.Tables[0].Columns["Dept"].ColumnName;
_DeptList.DataBind();
_DeptList.AutoPostBack = true;
placeholder.Controls.Add(_Lbl1);
placeholder.Controls.Add(_spacerlbl);
placeholder.Controls.Add(_DeptList);
placeholder.Controls.Add(_spacerlbl);
placeholder.Controls.Add(_Lbl);
placeholder.Controls.Add(_SubList);
placeholder.Controls.Add(_spacer);
}
}
protected void DeptList_Index_Changed(Object sender, EventArgs e)
{
\\Based on the selection in DropDownList2, a list will be loaded from a
\\database to DropDownList3
}
上述事件是基于从DropDownList (1)中选择数字n触发的。如果我从DropDownList (2)中选择一个项目,数据将从数据库生成并添加到DropDownList (3)。问题是当我尝试从DropDownList (2)中选择一个项目时,动态创建的控件会丢失。如何克服这个问题?
我什至用谷歌搜索了它,发现PostBack
我的代码中缺少一些东西。但我无法找到相关资源来了解它