简体   繁体   中英

Dynamic drop down list's selected Index Changed event always return the first value

So,

I have a drop down list whish fill by a result of SQL query in my event page_Load. What i want to do it's get the current value when the event selectedIndexChanges on my drop down list is fired and put it in a textbox.

Look my code below.

  • My drop down list definition: <asp:DropDownList ID="ddProfil" runat="server" Width="550" AutoPostBack="True" OnSelectedIndexChanged="ddProfil_SelectedIndexChanged" >

  • My page load event: protected void Page_Load(object sender, EventArgs e) { loadDDProfil(Request.QueryString["sitename"]); } protected void Page_Load(object sender, EventArgs e) { loadDDProfil(Request.QueryString["sitename"]); }

  • Function which load the drop down list:

 protected void loadDDProfil(string siteName)
        {

            SqlCommand requete = new SqlCommand();
            requete.Connection = connWeb.ConnectionToDb;

            requete.CommandType = System.Data.CommandType.Text;
            string strReq = "ps_get_all_IndexProfil " + "MRF";
            requete.CommandText = strReq;
            DataTable dtPrf = connWeb.ExecuteQueryDB(requete);

            SqlDataAdapter adapter = new SqlDataAdapter(requete);
            adapter.Fill(dtPrf);

            var dtSource = from p in dtPrf.AsEnumerable()
                           select new {
                               ind = p.Field("IndexProfil"),
                               DisplayedField = String.Format("{0} [ {1} ]", p.Field("NomProfil"), p.Field("Description"))
                           };

            ddProfil.DataSource = dtSource;
            ddProfil.DataValueField = "ind";
            ddProfil.DataTextField = "DisplayedField";
            ddProfil.DataBind();
            ddProfil.SelectedIndexChanged += ddProfil_SelectedIndexChanged;
  • And the event Selected Index Changed:

  public void ddProfil_SelectedIndexChanged(object sender, EventArgs e)
        {

               string s = ddProfil.SelectedValue;
        }

Thank you, for your help.

I believe your answer is here https://taditdash.wordpress.com/2014/05/21/why-dropdownlist-selectedvalue-not-working-inside-selectedindexchanged-event/

On your page load event try adding this:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        loadDDProfil(Request.QueryString["sitename"]);
    }
}

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