3

I'm trying to employ the strongest OOP I can muster in developing a web application, but I'm having issues adding event handlers to my objects as I create them using code. I'm sure it's a fairly simple solution that I just keep passing up, but I'm at a loss as to what to try next. Below is some test code I've been playing with, just trying to get a button press to go do something.

(Imagine there's a break point on the line "int i;")

    Button b = new Button();
    b.Text = "Do Something";
    b.Attributes.Add("runat", "server");
    b.Attributes.Add("OnClick", "click");
    form1.Controls.Add(b);

    private void click(object sender, EventArgs e)
    {
        int i;
    }

Since this is a new button created by my Page_Load, I can't just hardcode the XHTML. Debugging never hits my breakpoint. I haven't had any more success with CheckBoxes either.

1
  • Usually you use delegate functions in C#. What framework specifically are you targeting? Commented Feb 14, 2013 at 1:19

2 Answers 2

11

You have to subscribe to the Click event:

Button b = new Button();
b.Text = "Do Something";
b.Click += click;
form1.Controls.Add(b);

private void click(object sender, EventArgs e)
{
    int i;
}

By adding the onclick Attribute to the Button's Attributes collection, it will be rendered as an attribute on the HTML input tag. In that case you could use it to execute some javascript code on the client side.

b.Attributes.Add("onclick", "alert('Hey')");

//Will render the button as
<input type="submit" name="x" value="Do Something" onclick="alert('Hey')">
Sign up to request clarification or add additional context in comments.

Comments

1

You can do:

Button b = new Button();
b.Text = "Do Something";
b.Click += new EventHandler((s, ev) =>
                        {
                            int i;
                        });
form1.Controls.Add(b);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.