簡體   English   中英

從另一個下拉列表中選擇一個值后填充下拉列表

[英]Populating dropdown list after selecting a value from another dropdown list

我希望能夠在從另一個下拉列表中選擇一個值后填充下拉列表(ddlExercise)(ddlType)目前我從sql查詢中獲取ddlType下拉列表的值,該查詢填充了下拉列表但是當我選擇時第二個下拉列表仍然是空的。 我在ddlType下拉列表中有3個值(Gym,Core,Cardio),一旦我選擇其中一個,我使用dropdownlist.selectedvalue來檢索其相應的結果。 這是我的代碼:

    protected void Page_Load(object sender, EventArgs e)
    {
       SqlConnection con = new SqlConnection(@"Con String");


        if (!IsPostBack)

        { BindExerciseType(); }
    }

     public void BindExerciseType()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select ExerciseType from ExerciseType", con);
        SqlDataReader dr = cmd.ExecuteReader();
        ddlType.DataSource = dr;
        ddlType.Items.Clear();
        ddlType.Items.Add("--Please Select country--");
        ddlType.DataTextField = "ExerciseType";
        ddlType.DataValueField = "ExerciseType";
        ddlType.DataBind();
        con.Close();



    }

    public void BindExercise()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select ExerciseName from ExerciseDisplay   Where TypeName='" + ddlType.SelectedValue + "'", con);
        SqlDataReader dr = cmd.ExecuteReader();
        ddlExercise.DataSource = dr;
        ddlExercise.Items.Clear();
        ddlExercise.Items.Add("--Please Select country--");
        ddlExercise.DataTextField = "ExerciseName";
        ddlExercise.DataValueField = "ExerciseName";
        ddlExercise.DataBind();
        con.Close();

    }

        protected void ddlExercise_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindExercise();
    }

任何想法為什么這可能是錯的? 我在兩個下拉列表中都將autopostback屬性設置為true。 任何幫助將不勝感激!

你的第二個SQL查詢是錯誤的。 WHERE和TypeName之間應該有一個空格。 像這樣 :

SqlCommand cmd = new SqlCommand("select ExerciseName from ExerciseDisplay   Where TypeName='" + ddlType.SelectedValue + "'", con);

問題是你的事件,你的事件是為了另一個下拉,你的事件應該是:

protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
{
    BindExercise();
}

對代碼的貢獻,如果使用數據源填充下拉列表,如果它們位於bind()之前,則不會顯示添加的項目。 您必須添加以下內容,以保留最新內容:

ddlType.Items.Insert(0, "--Please Select country--");

我希望我一直很有幫助,祝你好運。 (抱歉,我的英文)

問題出現在selectedIndexChanged函數中,當ddltype下拉列表的索引改變而不是dllExericese時,可能會觸發該問題,在使用autopost方法后,你應該確保dlltype selectedindex沒有改變,方法是在函數dlltype_selectedindexchanged中設置dlltype.SelectedIndex = dlltyp.selectedindex與dlltype下拉列表關聯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM