简体   繁体   中英

How Do I Add Event Handlers to .NET Buttons Programmatically?

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.

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')">

You can do:

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

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