Dynamically created DropDownList no firing event. yes, Autopostback is set to TRUE

后端 未结 2 1264
孤街浪徒
孤街浪徒 2021-01-28 07:15

Below is my code for a dynamic dropdownlist. It does generate the HTML properly. However, the event is not fired. And, when I change the event name to \"onchange\" it gives me a

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-28 08:08

    1) It doesn't work because you're not adding the attribute "AutoPostBack" the way you should.

    pValueCmbBox.Attributes.Add("runat", "server"); //doesn't make sense...it's just for decoration...because you can't use in page behind code
    pValueCmbBox.SelectedIndexChanged += new EventHandler(ddlParent_SelectedIndexChanged); //this line it's okay
    pValueCmbBox.Attributes.Add("OnSelectedIndexChanged", "ddlParent_SelectedIndexChanged"); //this it's not necessary at all...because you already specified through pValueCmbBox.SelectedIndexChanged
    pValueCmbBox.Attributes.Add("AutoPostBack", "True"); //this is the problem
    

    As you can see in here, SelectedIndexChanged "Occurs when the selection from the list control changes between posts to the server." . So you had a good idea regarding AutoPostBack = true; You should have written:

    pValueCmbBox.AutoPostBack = true;
    

    And now for the runat="server" problem you can set your page behind function as following:

    protected void ddlParent_SelectedIndexChanged(object sender, EventArgs e)
    {
     DropDownList c = (DropDownList)sender; //this is your pValueCmbBox that you set it in OnInit
     //more code here
    }
    

    2) onchange is for javascript, but for c#/vb you can use OnTextChanged
    3) You can do that, as you already tried...or the way i told you. :)

提交回复
热议问题