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 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; }
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With