繁体   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