简体   繁体   中英

private variables resetting between methods 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

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 eg 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; }
}

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

It is because the web is stateless. Here are some methods for passing data between pages.

ASP.net MVC: http://msdn.microsoft.com/en-us/library/dd394711(v=vs.100).aspx

ASP.net Webforms http://msdn.microsoft.com/en-us/library/6c3yckfw(v=VS.100).aspx

Hope this helps.

You can also use Session object to store information that you need between requests. Eg: Session["messageIdString"]=value

For more info : http://msdn.microsoft.com/en-us/library/ms178581(v=vs.100).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM