<div class="form-group col-lg-12">
<label for="ddl1">1:</label>
<asp:DropDownList ID="ddl1" name="ddl1" CssClass="form-control" runat="server" />
</div>
<div class="form-group col-lg-12">
<label for="ddl2">1:</label>
<asp:DropDownList ID="ddl2" name="ddl2" CssClass="form-control" runat="server" required />
</div>
我試圖根據ddl1的值選擇ddl2的下拉列表項目。因此,「if」函數的Get2爲& Get2。 注意:每個ddl的數據將來自我的數據庫中的表格。根據第一個選擇的下拉列表項加載第二個下拉列表項目
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddl1Get();
Get1();
Get2();
}
#region "Function"
if (ddl1.SelectedItem.Value == "1")
{
Get1();
}
else if (1.SelectedItem.Value == "2")
{
Get2();
}
#endregion
}
#region "Function"
if (ddl1.SelectedItem.Value == "1")
{
Get1();
}
else if (ddl1.SelectedItem.Value == "2")
{
Get2();
}
#endregion
void Get1()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ID, Category FROM Table1";
SqlDataReader dr = cmd.ExecuteReader();
ddl2.DataSource = dr;
ddl2.DataTextField = "Category";
ddl2.DataValueField = "Category";
ddl2.DataBind();
con.Close();
ddl2.Items.Insert(0, new ListItem(" ", ""));
}
void Get2()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ID, Category FROM Table2";
SqlDataReader dr = cmd.ExecuteReader();
ddl2.DataSource = dr;
ddl2.DataTextField = "Category";
ddl2.DataValueField = "Category";
ddl2.DataBind();
con.Close();
ddl2.Items.Insert(0, new ListItem(" ", ""));
}
void ddlGet()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ID, Category FROM Table0";
SqlDataReader dr = cmd.ExecuteReader();
ddl1.DataSource = dr;
ddl1.DataTextField = "Category";
ddl1.DataValueField = "Category";
ddl1.DataBind();
con.Close();
ddl1.Items.Insert(0, new ListItem(" ", ""));
}
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddl1.SelectedItem.Value == "1")
{
Get1();
}
else if (ddl1.SelectedItem.Value == "2")
{
Get2();
}
}
你的Page_Load事件是什麼樣子..這是你應該檢查IsPostBack等事情的地方。你甚至試圖通過使用調試器的代碼..?我也會認爲你在Select查詢中的第二個下拉列表,你會看到一個Where子句... – MethodMan
也是爲什麼你向我們展示'void Get2()'方法兩次是你粘貼代碼中的一個錯誤。 。? – MethodMan
@MethodMan我不好,我現在修好了。 – Allocen