开发者

EventHandler in asp.net

开发者 https://www.devze.com 2023-03-31 11:37 出处:网络
I am trying to create an event handler which displays some text whenever a button is clicked . I can do it using

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 m开发者_开发知识库e 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";
}


Event Handler should be initialized in Page Load or Page_Init event btn1.Click += new EventHandler(OnClick);

0

精彩评论

暂无评论...
验证码 换一张
取 消