简体   繁体   中英

EventHandler in asp.net

I am trying to create an event handler which displays some text whenever a button is clicked .

I can do it using

<asp:button id="btn1" runat="server" onClick="btn1_clicked" />
<asp:label id="lbl1" runat="server"  />

in the aspx.cs file

public void btn1_clicked(object sender, EventArgs e)
{
   lbl1.Text = "Text goes here";
}

However when I try to create the event handler using

public void btn1_clicked(object sender, EventArgs e)
{
   btn1.Click += new EventHandler(OnClick);
}
public void OnClick(object sender, EventArgs e)
{
  lbl1.Text = "Text goes here";
}

It gives me an error.

What is the correct way to create the event handler?

You could create the event handler at

Page_Load

btn1.Click += (o,e)=>{  lbl1.Text = "";  }

you don't need to create a new event handler because btn1_clicked is your click event handler. Just put your code in it.

public void btn1_clicked(object sender, EventArgs e)
{
  lbl1.Text = "Text goes here";
}

应该在Page Load或Page_Init事件btn1中初始化事件处理程序。点击+ = new EventHandler(OnClick);

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