0

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 compile error saying that it couldn't find the script. By it's there in my code-behind.

Also, I'm adding this in the OnInit page event.

pValueCmbBox.Attributes.Add("runat", "server");
pValueCmbBox.SelectedIndexChanged += new EventHandler(ddlParent_SelectedIndexChanged);
pValueCmbBox.Attributes.Add("OnSelectedIndexChanged", "ddlParent_SelectedIndexChanged");
pValueCmbBox.Attributes.Add("AutoPostBack", "True");
  1. Why isn't OnSelectedIndexChanged being fired?
  2. Is "onchange" only for calling javascript?
  3. Should I implement this as an ASCX instead?
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user259286
  • 977
  • 3
  • 18
  • 38

2 Answers2

0

To answer my own question...

I ended up making an ASCX out of it and now it works fine!

user259286
  • 977
  • 3
  • 18
  • 38
0

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. :)

Community
  • 1
  • 1
Michael
  • 649
  • 6
  • 9