我有一个问题,我一直在争论一段时间,我的动态DropDownList总是从数据库返回到第一项,我已经做了一些研究如何解决这个问题,包括为页面启用Viewstate和DropDownList并放置if(!Page.IsPostback)上的代码,但问题仍然存在!
这是我的代码:
if (!Page.IsPostBack)
{
string appType2 = Session["applicationType"].ToString();
if (appType2 == "nur")
{
FetchApplicationFeeFromDB("NURSERY");
this.ddlAppClass.Items.Clear();
this.ddlApplicationType.Items.Insert(0, "NURSERY SCHOOL");
string query = string.Format("SELECT [Teaching Room Category] ,[Description] FROM [Corona Schools_ Trust Council$Teaching Room Level] WHERE [Teaching Room Category] = '{0}'", "NURSERY");
BindDropDownList(this.ddlAppClass, query, "Description", "Teaching Room Category", "---Select---");
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
string conString = ConfigurationManager.ConnectionStrings["DatabaseDemo Database NAV (8-0)1"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
con.Close();
}
}
ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
protected void ddlAppClass_SelectedIndexChanged(object sender, EventArgs e){
if (this.ddlAppClass.SelectedIndex != 0) {
txtDateOfBirth.Enabled = true;
} else {
txtDateOfBirth.Enabled = false;
}
}
我的DropdownList源代码:
<asp:DropDownList ID="ddlAppClass" runat="server" AutoPostBack="True" Height="20px" Width="188px" OnSelectedIndexChanged="ddlAppClass_SelectedIndexChanged" EnableViewState="true"></asp:DropDownList>
OnSelectedIndexChanged代码:
protected void ddlAppClass_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.ddlAppClass.SelectedIndex != 0)
{
txtDateOfBirth.Enabled = true;
}
else
{
txtDateOfBirth.Enabled = false;
}
}
答案 0 :(得分:0)
每次加载页面时都需要绑定项目,而不仅仅是在什么时候!PostBack。当您回发时,页面是从aspx重建的,并且在代码中设置了(尝试)选定的值,但在您的情况下,下拉列表将为空,因为您没有调用BindDropDownList,因此无法设置其选定值并且您得到零