ListBox1连接到SQL数据库,并将查询的数据绑定到ddCountries(DropDownList)。选择DropDownList项目时,应该更新页面上其他位置的标签,但是由于某些原因,在应用程序运行时根本无法访问ddCountries_SelectedIndexChanged方法。
是,AutoPostBack设置为“ true”。
Default.aspx
ListBox1:
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection countriesConnection = new SqlConnection();
countriesConnection.ConnectionString =
System.Web.Configuration.WebConfigurationManager.ConnectionStrings["CSharpClass1ConnectionString"].ConnectionString;
SqlCommand cmd = countriesConnection.CreateCommand();
int ContID = Convert.ToInt32(ListBox1.SelectedValue);
try
{
string query = "SELECT * FROM Country WHERE ContinentId=" + ContID + ";";
SqlDataAdapter adpt = new SqlDataAdapter(query, countriesConnection);
DataTable dt = new DataTable();
adpt.Fill(dt);
ddCountries.DataSource = dt;
ddCountries.DataBind();
ddCountries.DataTextField = "CountryName";
ddCountries.DataValueField = "ContinentId";
ddCountries.DataBind();
}
catch (Exception ex)
{
}
finally
{
cmd.Dispose();
countriesConnection.Close();
}
}
DropDownList:
<asp:DropDownList ID="ddCountries" runat="server" Height="16px" Width="238px" OnSelectedIndexChanged="ddCountries_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem Text="None" value=""></asp:ListItem>
</asp:DropDownList>
Default.aspx.cs
protected void ddCountries_SelectedIndexChanged(object sender, EventArgs e)
{
lblThankYou.Visible = true;
lblThankYou.Text = "You have selected " + ddCountries.SelectedValue.ToString() + "!";
}
没有错误消息,标签(lblThankYou)根本就不会更新。根据调试,该方法永远不会被访问。
答案 0 :(得分:0)
您应该使用UpdatePanle和ScriptManager:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" ChildrenAsTriggers="true" >
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>item 1</asp:ListItem>
<asp:ListItem>item 2</asp:ListItem>
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
throw new NotImplementedException();
}