简体   繁体   中英

Getting the selected index of drop down list

I am using c# and asp.net in my project.I wanted to get the selectedindex of the dropdownlist but I am getting always as 0.Here is my code of binding the dropdown list with data

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();
        }

And I am trying to get selected index by:

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

        techID = DropDownList2.SelectedIndex;
    }

Here is my page_load:

protected void Page_Load(object sender, EventArgs e) {

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

}

Please tell me where I am going wrong.

That is because you refill the drop down list in page load without checking that it is not post back.

Warping your try-catch (drop down fill) code with

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

should solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM