TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

How to raise an ItemCommand event from a UserControl

This was pissing me off today. I had a datagrid that I needed to capture an OnItemCommand event for several controls in 1 to n number of DataGridItem objects. One of these controls in the datagrid was a UserControl that someone else created. It turns out, it is really not difficult, but I thought I'd share in case anyone else runs across having to figure this out.

 

public class SeanControl : System.Web.UI.UserControl

{

  private void MyDropDown_SelectedIndexChanged(object sender, System.EventArgs e)

  {

    if (this.SelectedIndexChanged != null)

    {

        this.SelectedIndexChanged(this, EventArgs.Empty);

    }

    this.OnCommand(new CommandEventArgs(String.Empty, e));

  }

 

  protected virtual void OnCommand(CommandEventArgs e)

  {

    base.RaiseBubbleEvent(this, e);

  }

}

 

 

// Code in aspx page to handle datagrid ItemCommand...

private void MyGrid_ItemCommand(object source, DataGridCommandEventArgs e)

{

    if(e.CommandSource is SeanControl)

    {

        // Do stuff

    }

}


Digg!

posted on Friday, August 06, 2004 12:11 PM

Feedback

# re: How to raise an ItemCommand event from a UserControl 11/8/2004 7:11 AM Simon C

Thanks so much for this !!!

i had exactly the same problem and couldnt work out why the user control would not fire my onBubbleEvent in the parent page. I looked all over the internet and was about to find an alternative solution before finding this page.. and all the time the message came in throught the onItemCommand handler !!

happy days !

# re: How to raise an ItemCommand event from a UserControl 4/26/2005 4:24 AM Ankur

Well can you help writing this code snippet in VB.NET and also please tell that is that class created as a separate class or the code is written on the same page where you have the datagrid.Please help I am in real need of this quickly.
Thanks
Ankur