C# why is int value keep getting reset to 0?

Goal: Keep value of int (professorIndex) reachable when I get to the button click method (btnUpdateAvailability_Click())

Problem: The value gets set correctly initially, then somehow goes to 0

What ive tried: Starting variable at class level. Getting rid of any other references to it, including commenting out where it was set to 0

What am I missing?

C#:

public partial class SiteMaster : MasterPage
{
        private int professorIndex;
        protected void Page_Load(object sender, EventArgs e) {
        //some stuff
        }
        
        protected void cbUpdateAvailability_Click(object sender, EventArgs e)
        {
        CheckBox cbSender = (CheckBox)sender;
        professorIndex = getProfessorIndexCB(cbSender.ClientID);
        //at this point, professorIndex is 1, which is what I want/expect
        }
        
        
        public int getProviderIndexCB(string cbSender)
        {
            //professorIndex = 0;
            switch (cbSender)
            {
                case "chkOnOff1":
                    professorIndex = 0;
                    break;
                case "chkOnOff2":
                    professorIndex = 1;  //This is the one that is triggered
                    break;
            }
            return professorIndex;
        }
        
        
        protected void btnUpdateAvailability_Click(object sender, EventArgs e)
        {
        //at this point, professorIndex is 0, no clue why. It should be one
        }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Below a simple demo to store a value you want to persist in a Session and get it back on PostBack.

public int professorIndex = 0;

protected void Page_Load(object sender, EventArgs e)
{
    //check for postback
    if (!IsPostBack)
    {
        //set the index
        professorIndex = 10;

        //store the index in a session
        Session["professorIndex"] = professorIndex;
    }
}


protected void Button1_Click(object sender, EventArgs e)
{
    //check if the session exists
    if (Session["professorIndex"] != null)
    {
        //cast the session back to an int
        professorIndex = (int)Session["professorIndex"];
    }

    //show result
    Label1.Text = $"The professor index is {professorIndex}.";
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x