Click here to Skip to main content
15,889,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a code behind file that on page load sets up a form. this form has a dropdownlist to select which form you'd like to view.

When selecting a different view a onSelectedIndexChanged method is called, i can see this is being called. When the index changes it sets a global boolean depending on what is selected, e.g if
"formulation" is selected global bool form = true;

therefore later when i have filled in the form and click submit the onClick event is fired, but it still thinks the bool is false, it is not recognising the change in variable value,

is there anyone out there that can clear this up for me.. basic code below

C#
public partial class ProductSearch : PageBase
{
    StringBuilder builder;
    List<string> errorMessages;
    Document doc;
    bool formulationSearch = false;
    bool batchSearch = false;

    protected void Page_Load(object sender, EventArgs e)
    {


        if (!Page.IsPostBack)
        {
            errorMessages = new List<string>();
            SetupBatchForm();
            SetupLanguageSelect();
            language_select.SelectedValue = "2";
        }
    }
private void SetupBatchForm()
    {
        search_by.SelectedValue = "batch";
        batchSearch = true;
        batch_input.Visible = true;
        batch_help.Visible = true;
        formulation_input.Visible = false;
        formulation_help.Visible = false;

     }

code Submit button onClick

C#
protected void SubmitSearch(object sender, EventArgs e)
    {
        Response.Write("Submited");
        Response.Write(batchSearch);
        if (batchSearch)
        {
            SubmitBatchSearch();
        }
        else
        {
            SubmitFormulationSearch();
        }
            
        
    }
Posted

1 solution

This is because webforms do not work like windows forms. When you set a variable it is only valid for that connection. When your page posts back all of your C# runs and then a bunch of html is sent to the client and you are disconnected. So, any variables you had set in your class are lost. The next time the page postsback, such as a button click, there is a new instance of your class created.

To persist information you may want to instead write the value into a hidden field or use the session or some other form of persistent storage.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900