简体   繁体   中英

Why won't my SelectedIndexChanged event fire in Button_Click?

protected void Button1_Click(object sender, EventArgs e)
{
    TableRow tb = new TableRow();
    TableCell tc = new TableCell();

    DropDownList db = new DropDownList();
    db.Items.Add("Bangalore");
    db.Items.Add("Mandya");
    db.Items.Add( "Hassan");

    tc.Controls.Add(db);
    tb.Controls.Add(tc);

    Table1.Controls.Add(tb);

    db.SelectedIndexChanged += db_SelectedIndexChanged;
    db.AutoPostBack = true;
}

private void db_SelectedIndexChanged(object sender, EventArgs e)
{
    label.text = "welcome";
}

When this code executes in the Button1_Click event, db_SelectedIndexChanged doesn't execute. However, when I place the same Button1_Click code block in the Page_Load event, db_SelectedIndexChanged executes.

What may be the reason behind this?

Try to put

db.SelectedIndexChanged += db_SelectedIndexChanged;
db.AutoPostBack = true;

In the Page_Load event.

Don't wrap db.SelectedIndexChanged += db_SelectedIndexChanged; in !Page.IsPostBack as the events need to be wired up on each load

You are creating a dynamic control. The event will not fire unless you create the control in the PreInit method of the page.

protected void Page_PreInit(object sender, EventArgs e)
{
    DropDownList db = new DropDownList();
    db.Items.Add("Bangalore");
    db.Items.Add("Mandya");
    db.Items.Add( "Hassan");
    db.SelectedIndexChanged += db_SelectedIndexChanged;
    db.AutoPostBack = true;

    tc.Controls.Add(db);
}

Check Page Life cycle for more info.

    protected void Button1_Click(object sender, EventArgs e)
   {
     TableRow tb = new TableRow();
     TableCell tc = new TableCell();

     DropDownList db = new DropDownList();
    db.Items.Add("Bangalore");`
    db.Items.Add("Mandya");
    db.Items.Add( "Hassan");

    tc.Controls.Add(db);
    tb.Controls.Add(tc);

   Table1.Controls.Add(tb);

   db.SelectedIndexChanged += db_SelectedIndexChanged;
   db.AutoPostBack = true;
   db_SelectedIndexChanged(null,null); // use this line, i hope it will work now.

  }

  private void db_SelectedIndexChanged(object sender, EventArgs e)
  {
    label.text = "welcome";
  }

You can try this one.

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