The task is to count the number of clicks in a webform.
Here is the code.
public partial class _default : System.Web.UI.Page
{
int count = 1;
private void Page_Load(object sender, System.EventArgs e)
{
Button btn = new Button();
btn.Text = "Click Me";
btn.Click += btn_Click;
Label lbl = new Label();
form1.Controls.Add(btn);
form1.Controls.Add(lbl);
}
protected void btn_Click(object sender, EventArgs e)
{
count++;
//Label1.Text = count.ToString();
}
}
The problem is that lbl is not recognised inside btn_Click() … I can’t figure it out… can anyone suggest?
You need to declare lbl outside the page_load method than it will be available to you in button click like this.
Because if you create label in the page_load scope of the variable is limited to that method only. So either you declare the label outside the method like as I did or you can give id to label and than search it using
FindControlmethod.