我有兩個下拉菜單來顯示類別,其次顯示與所選類別相關的子類別。下拉列表沒有獲取第二個和第三個列表的值
情景是。類別值來自表格,並且正確讀取。問題是,當我選擇第一個類別時,第二個下拉菜單顯示了確切的子類別。但是,當我選擇第二個類別時,它不會顯示與其相關的子類別。 請看到我已經綁定的類別和子類別爲同一獲取data.:-
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultSQLConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select CategoryName from dbo.CategoriesForMerchant where ParentId is null", conn);
SqlDataReader dr = cmd.ExecuteReader();
ddlCategories.DataSource = dr;
ddlCategories.Items.Clear();
ddlCategories.DataTextField = "CategoryName";
ddlCategories.DataValueField = "CategoryName";
ddlCategories.DataBind();
ddlCategories.Items.Insert(0, new ListItem("--Select Category--", "0"));
conn.Close();
}
}
protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultSQLConnectionString"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from CategoriesForMerchant where ParentId=0" + ddlCategories.SelectedIndex + "", conn);
SqlDataReader dr = cmd.ExecuteReader();
ddlSubCategories.DataSource = dr;
ddlSubCategories.Items.Clear();
ddlSubCategories.DataTextField = "CategoryName";
ddlSubCategories.DataValueField = "CategoryName";
ddlSubCategories.DataBind();
ddlSubCategories.Items.Insert(0, new ListItem("--Select Sub Category--", "NA"));
conn.Close();
}
另請參見SQL表結構的代碼: -
CREATE TABLE [dbo].[categoriesformerchant]
(
categoryid INT IDENTITY(1,1) NOT NULL,
categoryname NVARCHAR(50) NOT NULL,
parentid INT NULL,
CONSTRAINT [pk_CategoriesForMerchant] PRIMARY KEY CLUSTERED (categoryid ASC)
)goALTER TABLE [dbo].[categoriesformerchant] WITH CHECK ADD CONSTRAINT [fk_subcategories] FOREIGN KEY(parentid) REFERENCES [dbo].[categoriesformerchant] ([categoryid])goALTER TABLE [dbo].[categoriesformerchant] CHECK CONSTRAINT [fk_subcategories]go
也請參閱HTML代碼: -
<asp:DropDownList ID="ddlCategories" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlCategories_SelectedIndexChanged">
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqCategory" runat="server" ControlToValidate="ddlCategories" ErrorMessage="Please select the category" InitialValue="0"></asp:RequiredFieldValidator>
<br />
<asp:DropDownList ID="ddlSubCategories" runat="server" AutoPostBack="True">
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqSubCategory" runat="server" ControlToValidate="ddlSubCategories" ErrorMessage="Please select the sub-category" InitialValue="0"></asp:RequiredFieldValidator>
請粘貼HTML] – 2014-11-06 06:36:31
@HardikParmar:看編輯的問題 – BNN 2014-11-06 06:38:09
首先刪除的 from HTML Bcoz您已經在Class文件中寫入了該代碼 –
2014-11-06 06:39:30