Вопрос

I am not getting the right value of flag after setting it inside ButtonAdd_Click. The scenario is when I click on ButtonAdd, that the protected void ButtonAdd_Click calls the private AddNewRowToGrid() which sets the flag=true which is used by protected void btn3_click.

public partial class WebForm3 : System.Web.UI.Page
{
    bool flag = false;
    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)
        {
        }
    }
}
Это было полезно?

Решение

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;
        }
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top