The problem you are facing is the fact that each button click is a new postback to the server that will create a new instance of your class to handle each request.
This means that setting the flag
in between 2 postbacks, one when you click on the ButtonAdd
button and one when you click on the btn3_Click
button has no effect as you noticed yourself
The easiest solution is to store this flag
in the ViewState
(remark: be very careful about what you want to store in the ViewState
as it will be send back and forth with each request)
either way if you change your code like this, then it'll do what you were expecting:
public partial class WebForm3: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//MyCode
}
private void AddNewRowToGrid()
{
Flag = true;
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void btn3_Click(object sender, EventArgs e)
{
if (Flag == true)
{
}
}
private bool Flag
{
get
{
bool? flag = ViewState["flag"] as bool?;
return flag.HasValue ? flag.Value : false;
}
set
{
ViewState["flag"] = value;
}
}
}