Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private variables resetting between methods c#

Tags:

scope

c#

This is probably the biggest noob question ever but I'm confused as to why my private variables, when they are set in one method, gets reset in another. I have something like this in my code:

namespace Project.Messages
{
public partial class Inbox : System.Web.UI.Page
{

    private static int selectedIndex;
    private static string messageIDString;
    private static int messageID; 

    //select message to view
    protected void viewMessage(object sender, GridViewCommandEventArgs e)
    {
            //get index
            selectedIndex = MsgInbox.SelectedIndex;
            if (int.TryParse(e.CommandArgument.ToString(), out selectedIndex))
            {
                //get selected dataKey, convert to a int
                messageIDString = MsgInbox.DataKeys[selectedIndex].Value.ToString();
                messageID = Convert.ToInt16(messageIDString);
            }
     }

    //select message to delete
    protected void delBTN_Click(object sender, EventArgs e)
    {

        SqlCommand com = new SqlCommand("DELETE FROM Messages WHERE MessageID =    @param1", conn);
        conn.Open();

        com.Parameters.AddWithValue("param1", messageID);
    }

So if I click a message, messageID will be set and the message will be displayed. When I click to delete message after that though, it looks like the variable is resetting/is not the same value as previously set. Do I need to use a static variable or something to achieve this?

Thanks

like image 482
Kevin Avatar asked Oct 25 '12 20:10

Kevin


2 Answers

That is the behaviour. When there is postback, all variables are reset and reassigned. You can use session or viewstate or store the value in a control on the page which is already part of the viewstate e.g. in an hidden field

public int messageID
{
   get 
   { 
      int retVal = 0;
      if(ViewState["messageID"] != null)
         Int32.TryParse(ViewState["messageID"].ToString(), out retVal); 

      return retVal;
   }
   set { ViewState["messageID"] = value; }
}
like image 148
codingbiz Avatar answered Nov 16 '22 02:11

codingbiz


It's because of ASP.NET, not C#. You need to save your variables in viewstate. See: variable initialized in class loses its previous value with the page loading

like image 5
aquinas Avatar answered Nov 16 '22 03:11

aquinas