Tech Off Thread

17 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Attaching events to objects created in code-behind...

Back to Forum: Tech Off
  • User profile image
    jsampsonPC

    If I created a button, and wanted it to post back to the server and call a server-side function, how would I do that when I create the object in codebehind?

  • User profile image
    JChung2006

    Here's a simple example:

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        Button button = new Button();
        button.ID = "Button1";
        button.Text = "Button1";
        PlaceHolder1.Controls.Add(button);
        button.Click += new EventHandler(Button1_Click);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "Button1_Click";
    }

    The gist of it is that you need to have some sort of server-side object with an event handler attached to your server-side function.  Be sure to put ID's on your dynamically created controls.

  • User profile image
    Sven Groot

    On thing you must know when trying to do this is that, for the event to work properly, you must create the control before the Load event, and the control must also be created, with the same ID, after the postback. The viewstate doesn't store your dynamically generated control tree, so make sure you can recreate it after the postback.

  • User profile image
    cheong

    Btw, if you're using the webform stub created by VS.NET 2003, just insert your "custom object creation method" behind the InitializeComponent() call in the OnInit() method. The method is located in the "Web Form Designer generated code" region.

    Recent Achievement unlocked: Code Avenger Tier 4/6: You see dead program. A lot!
    Last modified
  • User profile image
    stevo_

    You can also do auto event wireup (although I wouldn't personally), by turning it on in the page directive.

    Say you have a button control ButtonSubmit, you could then make a method called ButtonSubmit_Click with sender and eventargs which would get hooked up. Personally I feel this method is a little strange as no where really explicitely shows the event wireup.

    VB.NET is another thing, I'm pretty sure VB ignores the auto event wireup and just uses 'handles' syntax.

  • User profile image
    Sven Groot

    Neither auto event wireup nor VB's handles syntax apply to dynamically generated controls, only to those that are defined in the aspx page.

  • User profile image
    stevo_

    Ah sorry I misread the question, usually people have difficulty in linking controls from the aspx file to the code behind. The event model in the code behind is otherwise the same as anything else!

  • User profile image
    jsampsonPC

    Okay, I'm creating the button in the Init() portion of the life-cycle. I'm not exactly sure I've got the syntax right....it's frustrating, because once I get this little hurdle out of the way, I'll be snowballing down a hill of progress!

    Dim myNewBtn As Button = New Button

    myNewBtn.ID = dr("SOptID").ToString()

    myNewBtn.Text = "Testing"

    myNewBtn.Click &= New EventHandler(Button1_Click)

  • User profile image
    stevo_

    For VB you will want:

    AddHandler myNewBtn.Click, AddressOf Button1_Click

  • User profile image
    jsampsonPC

    AddHandler is working gloriously! I am unable to pass values through as parameters though - since this AddHandler wants a subroutine with no parenthesis, how do I pass values through during the call?

    I'm building a large table that looks similar to:

    edit / del || ProductTitle || $0.00
    edit / del || ProductTitle || $0.00
    edit / del || ProductTitle || $0.00

    Where 'edit' and 'del' are LinkButtons that need to post back to the page, call a WebService, and report exactly which product to edit, or delete. So I was trying to pass the ProductID and the OrderID through in the AddHandler...

    ' Add our events to our buttons

    AddHandler deltLink.Click, AddressOf deleteProduct(dr("StandingOrderID"), dr("StandingProductID"))

    Public Sub deleteProduct(ByVal OrderID As Integer, ByVal ProductID As Integer)

    Page.Title = "Deleted " & ProductID.ToString()

    End Sub

  • User profile image
    phreaks

    jsampsonPC wrote:
    AddHandler is working gloriously! I am unable to pass values through as parameters though - since this AddHandler wants a subroutine with no parenthesis, how do I pass values through during the call?

    I'm building a large table that looks similar to:

    edit / del || ProductTitle || $0.00
    edit / del || ProductTitle || $0.00
    edit / del || ProductTitle || $0.00

    Where 'edit' and 'del' are LinkButtons that need to post back to the page, call a WebService, and report exactly which product to edit, or delete. So I was trying to pass the ProductID and the OrderID through in the AddHandler...

    ' Add our events to our buttons

    AddHandler deltLink.Click, AddressOf deleteProduct(dr("StandingOrderID"), dr("StandingProductID"))

    Public Sub deleteProduct(ByVal OrderID As Integer, ByVal ProductID As Integer)

    Page.Title = "Deleted " & ProductID.ToString()

    End Sub



    I don't think you can do it like that.

    Can't you add some parameters to the link button, and grab those through the eventargs passed to the click event?

    Why does VB look so complicated?

  • User profile image
    Rotem Kirshenbaum

    jsampsonPC wrote:
    AddHandler is working gloriously! I am unable to pass values through as parameters though - since this AddHandler wants a subroutine with no parenthesis, how do I pass values through during the call?

    I'm building a large table that looks similar to:

    edit / del || ProductTitle || $0.00
    edit / del || ProductTitle || $0.00
    edit / del || ProductTitle || $0.00

    Where 'edit' and 'del' are LinkButtons that need to post back to the page, call a WebService, and report exactly which product to edit, or delete. So I was trying to pass the ProductID and the OrderID through in the AddHandler...

    ' Add our events to our buttons

    AddHandler deltLink.Click, AddressOf deleteProduct(dr("StandingOrderID"), dr("StandingProductID"))

    Public Sub deleteProduct(ByVal OrderID As Integer, ByVal ProductID As Integer)

    Page.Title = "Deleted " & ProductID.ToString()

    End Sub



    Couple of things:
    1) The Click event handler has to be with the right signature (gets Object sender, EvenetArgs e)
    2) You don't pass parameters in the event binding. Your event handler should get them in it's method body (Sorry it's in C#, my VB is rusty):

    private void button_click(object sender, EventArgs e)
    {
    // Get the right parameters from somewhere...
       int orderId = ...;
       int productId = ...;

       DeleteProduct(orderId , productId);
    }

    3) Why don't you use the GridView capabilities ? It has an edit / delete/ update column etc. Why not use it ?

    Hope this helps you.

  • User profile image
    JChung2006

    Rotem Kirshenbaum wrote:
     Why don't you use the GridView capabilities ? It has an edit / delete/ update column etc. Why not use it ?
    Some people prefer reinventing the wheel apparently. /shrug

  • User profile image
    jsampsonPC

    phreaks wrote:
    ...Can't you add some parameters to the link button, and grab those through the eventargs passed to the click event?


    That's what I'm trying to figure out... Smiley

    Rotem" wrote:
    ...Why don't you use the GridView capabilities ?


    Because what I showed you as my example is a much simplified version. The result requires conditional-formatting based upon what is in each row, etc. Some fields should have colspanning, etc, so I couldn't really use the GridView.

    Jonathan

  • User profile image
    jsampsonPC

    JChung2006 wrote:
    
    Rotem Kirshenbaum wrote:
     Why don't you use the GridView capabilities ? It has an edit / delete/ update column etc. Why not use it ?
    Some people prefer reinventing the wheel apparently. /shrug


    No, the GridView isn't sufficient visually.

  • User profile image
    JChung2006

    Code demonstrating passing arguments:

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        
        // <asp:LinkButton ID="EditButton" runat="server" CommandArgument="1" CommandName="Edit"
        //     Text="Edit" OnClick="LinkButton_Click" />
        LinkButton editButton = new LinkButton();
        editButton.ID = "EditButton";
        editButton.Text = "Edit";
        editButton.CommandName = "Edit";
        editButton.CommandArgument = "1";
        editButton.Click += new EventHandler(LinkButton_Click);
        PlaceHolder1.Controls.Add(editButton);

        // space
        LiteralControl whitespace = new LiteralControl();
        whitespace.Text = " ";
        PlaceHolder1.Controls.Add(whitespace);

        // <asp:LinkButton ID="DeleteButton" runat="server" CommandArgument="1" CommandName="Delete"
        //     Text="Delete" OnClick="LinkButton_Click" />
        LinkButton deleteButton = new LinkButton();
        deleteButton.ID = "DeleteButton";
        deleteButton.Text = "Delete";
        deleteButton.CommandName = "Delete";
        deleteButton.CommandArgument = "1";
        deleteButton.Click += new EventHandler(LinkButton_Click);
        PlaceHolder1.Controls.Add(deleteButton);
    }

    protected void LinkButton_Click(object sender, EventArgs e)
    {
        LinkButton button = sender as LinkButton;
        string commandName = button.CommandName;
        string commandArgument = button.CommandArgument;
        Label1.Text = string.Format("{0} {1}", commandName, commandArgument);
    }
  • User profile image
    JChung2006

    jsampsonPC wrote:
    No, the GridView isn't sufficient visually.

    GridView just generates an HTML table.  You can style the thing with CSS and customize the HTML it generates in each column with TemplateFields.

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.