簡體   English   中英

獲取選定的下拉列表索引

[英]Getting the selected index of drop down list

我在項目中使用c#和asp.net。我想獲取下拉列表的selectedindex,但我總是為0.這是將下拉列表與數據綁定的代碼

MySqlDataReader dr = null;
        try
        {
            //////////////Opening the connection///////////////

            mycon.Open();
            string str = "select category from lk_category";
            MySqlCommand command = mycon.CreateCommand();
            command.CommandText = str;
            dr = command.ExecuteReader();
            DropDownList1.DataSource = dr;
            DropDownList1.DataValueField = "category";
            DropDownList1.DataBind();
            dr.Close();
            str = "select technology from lk_technology";
            command.CommandText = str;
            dr = command.ExecuteReader();
            DropDownList2.DataSource = dr;
            DropDownList2.DataValueField = "technology";
            DropDownList2.DataBind();
        }
        catch (Exception ex) { Response.Write("Exception reding data" + ex); }
        finally
        {
            //dr.Close();
            mycon.Close();
        }

我正在嘗試通過以下方式獲取選定的索引:

 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        catID = DropDownList1.SelectedIndex+1;
    }
    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {

        techID = DropDownList2.SelectedIndex;
    }

這是我的page_load:

受保護的無效Page_Load(對象發送者,EventArgs e){

if (Session["valid"] == null)
    Response.Redirect("admin.aspx");
panel1();///If session valid then show panel1;

}

請告訴我我要去哪里了。

那是因為您在頁面加載中重新填充了下拉列表,而沒有檢查它是否沒有回發。

使用以下代碼扭曲嘗試捕獲(下拉填充)代碼

if (!this.IsPostBack)
{
    ...
}

應該解決問題。

暫無
暫無

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

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